pthread_create()函数和pthread_join()函数的用法
时间: 2023-11-30 19:41:41 浏览: 112
pthread_create()函数和pthread_join()函数都是用于多线程编程的函数。
pthread_create()函数用于创建一个新的线程,其原型如下:
```c
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
```
其中,第一个参数thread是指向线程标识符的指针,第二个参数attr是用来设置线程属性的,第三个参数start_routine是线程运行函数的起始地址,最后一个参数arg是运行函数的参数。
pthread_join()函数用于等待一个线程的结束,其原型如下:
```c
int pthread_join(pthread_t thread, void **retval);
```
其中,第一个参数thread是要等待的线程标识符,第二个参数retval是一个指向指针的指针,用来存储线程的返回值。
下面是两个伪代码用例,分别演示了pthread_create()函数和pthread_join()函数的用法:
1.使用pthread_create()函数创建一个新线程,并在新线程中运行func()函数:
```c
#include <pthread.h>
#include <stdio.h>
void func(void) {
pthread_detach(pthread_self());
pthread_exit(0);
}
int main(void) {
pthread_t sp = -1;
pthread_create(&sp, NULL, func, NULL);
return 0;}
```
2.使用pthread_create()函数创建一个新线程,并使用pthread_join()函数等待该线程结束:
```c
#include <pthread.h>
#include <stdio.h>
void func(void) {
return;
}
int main(void) {
pthread_t sp = -1;
pthread_create(&sp, NULL, func, NULL);
pthread_join(sp, NULL);
return 0;
}
```
阅读全文