根据实现线程的函数(pthread_creat pthread_exit ptread_join)尝试编写一个线程编程
时间: 2023-12-06 20:38:46 浏览: 91
以下是一个简单的使用pthread_create、pthread_exit和pthread_join实现的线程编程的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_func(void *arg) {
int *num = (int *)arg;
printf("Thread %d is running\n", *num);
pthread_exit(NULL);
}
int main() {
pthread_t threads[5];
int thread_args[5];
int i, result;
for (i = 0; i < 5; i++) {
thread_args[i] = i;
result = pthread_create(&threads[i], NULL, thread_func, &thread_args[i]);
if (result != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
}
printf("All threads are created\n");
for (i = 0; i < 5; i++) {
result = pthread_join(threads[i], NULL);
if (result != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
}
printf("Thread %d is joined\n", i);
}
printf("All threads are joined\n");
return 0;
}
```
该示例创建了5个线程,每个线程都会打印自己的编号,然后退出。主线程会等待所有子线程都退出后再退出。
阅读全文