linux中pthread_create
时间: 2023-09-20 18:04:29 浏览: 198
pthread_create是Linux中用于创建线程的函数。它的原型如下:
```c
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
```
该函数接受四个参数:
1. `thread`:指向pthread_t类型的指针,用于存储新线程的ID。
2. `attr`:指向pthread_attr_t类型的指针,用于指定新线程的属性。可以传入NULL,使用默认属性。
3. `start_routine`:指向线程函数的指针,新线程将从该函数开始执行。
4. `arg`:传递给线程函数的参数。
成功调用pthread_create函数将创建一个新线程,并将其ID存储在`thread`指向的内存中。新线程会执行`start_routine`指向的函数,并传入`arg`作为参数。
注意,创建线程后,需要使用pthread_join函数来等待线程结束并回收资源。另外,还可以使用pthread_detach函数将线程设置为分离状态,使其结束后自动回收资源。
这是一个简单的示例代码,演示了如何使用pthread_create创建并执行一个简单的线程:
```c
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg) {
int value = *(int*)arg;
printf("Thread function: value = %d\n", value);
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int value = 42;
if (pthread_create(&thread, NULL, thread_func, &value) != 0) {
fprintf(stderr, "Failed to create thread\n");
return 1;
}
// 等待线程结束
if (pthread_join(thread, NULL) != 0) {
fprintf(stderr, "Failed to join thread\n");
return 1;
}
printf("Main thread: Done\n");
return 0;
}
```
这个示例中,`thread_func`函数是一个简单的线程函数,它将打印传入的参数值。在主函数中,我们创建了一个新线程,并等待它结束后再输出一条消息。
希望这个回答能解决你的问题。如果还有其他疑问,请随时提问!
阅读全文
相关推荐


















