在 Linux 下创建线程通常可以使用 POSIX 线程库(pthread)。以下是一个简单的线程创建的示例,演示如何使用 pthread 创建和管理线程。
示例代码
c
#include
#include
#include
#include
#define NUM_THREADS 5
void* thread_function(void* threadid) {
long tid = (long)threadid;
printf("Thread %ld is running\n", tid);
sleep(1); // 模拟一些工作
printf("Thread %ld is exiting\n", tid);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;
for (t = 0; t < NUM_THREADS; t++) {
printf("Main thread: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, thread_function, (void*)t);
if (rc) {
printf("Error: unable to create thread %ld; error code: %d\n", t, rc);
exit(-1);
}
}
// 等待所有线程完成
for (t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}
printf("Main thread: all threads have completed.\n");
return 0;
}
编译和运行
1. 将上述代码保存到一个文件,例如 `threads_example.c`。
2. 使用 gcc 编译器编译这个程序,链接 pthread 库:
bash
gcc -o threads_example threads_example.c -lpthread
3. 运行生成的可执行文件:
bash
./threads_example
说明
- 使用 `pthread_create` 函数创建新的线程。该函数的参数包括线程 ID、线程属性、线程函数和传递给线程函数的参数。
- `pthread_exit` 用于在线程函数中退出线程。
- `pthread_join` 用于等待线程完成,可以保证主线程(即创建线程的线程)在所有线程完成之前不会退出。
- 程序中的 `sleep(1)` 是模拟线程工作,实际应用中可以替换为实际执行的任务。
注意事项
- 在使用线程时要注意资源共享和线程安全的问题,必要时可以使用互斥量(mutexes)来保护共享资源。
- 确保在编写多线程程序时对资源的使用是安全的,避免出现竞争条件。
查看详情
查看详情