【LinuxC】C语言线程(pthread)
warning:
这篇文章距离上次修改已过183天,其中的内容可能已经有所变动。
在C语言中,使用pthread库创建线程的基本步骤如下:
- 包含头文件
<pthread.h>
。 - 定义一个线程运行的函数(线程处理函数)。
- 创建线程,并传入线程处理函数和运行函数需要的参数。
- 等待线程结束或者 detach 线程。
以下是一个简单的例子:
#include <stdio.h>
#include <pthread.h>
// 线程处理函数
void* threadFunction(void* arg) {
printf("Hello from the thread!\n");
return NULL;
}
int main() {
pthread_t thread;
int ret;
// 创建线程
ret = pthread_create(&thread, NULL, &threadFunction, NULL);
if (ret != 0) {
// 创建线程失败
printf("Thread creation failed!\n");
return 1;
}
// 等待线程结束
pthread_join(thread, NULL);
return 0;
}
在这个例子中,我们定义了一个名为 threadFunction
的线程处理函数,并在 main
函数中创建了一个线程,该线程将执行 threadFunction
。然后我们调用 pthread_join
来等待线程的结束。
注意:在编译时需要链接 pthread 库,使用 -lpthread
选项。
评论已关闭