pthread_create和 pthread_join
时间: 2023-11-21 16:58:34 浏览: 131
linux创建线程之pthread_create的具体使用
pthread_create()和pthread_join()是Linux系统中用于创建和等待线程的函数。
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()函数创建和等待线程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function(void *ptr);
int main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int ret1, ret2;
// 创建线程1
ret1 = pthread_create(&thread1, NULL, print_message_function, (void *)message1);
if (ret1)
{
printf("Error: pthread_create() failed\n");
exit(EXIT_FAILURE);
}
// 创建线程2
ret2 = pthread_create(&thread2, NULL, print_message_function, (void *)message2);
if (ret2)
{
printf("Error: pthread_create() failed\n");
exit(EXIT_FAILURE);
}
// 等待线程1结束
ret1 = pthread_join(thread1, NULL);
if (ret1)
{
printf("Error: pthread_join() failed\n");
exit(EXIT_FAILURE);
}
// 等待线程2结束
ret2 = pthread_join(thread2, NULL);
if (ret2)
{
printf("Error: pthread_join() failed\n");
exit(EXIT_FAILURE);
}
printf("Main thread exiting\n");
exit(EXIT_SUCCESS);
}
void *print_message_function(void *ptr)
{
char *message;
message = (char *)ptr;
printf("%s\n", message);
pthread_exit(NULL);
}
```
阅读全文