pthread demo
时间: 2023-09-08 19:13:46 浏览: 36
下面是一个简单的 pthread 示例程序,它创建了两个线程,一个线程打印偶数,另一个线程打印奇数。
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_even(void *arg)
{
int i;
for (i = 0; i <= 10; i += 2) {
printf("%d\n", i);
}
return NULL;
}
void *print_odd(void *arg)
{
int i;
for (i = 1; i <= 10; i += 2) {
printf("%d\n", i);
}
return NULL;
}
int main()
{
pthread_t t1, t2;
if (pthread_create(&t1, NULL, print_even, NULL) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
if (pthread_create(&t2, NULL, print_odd, NULL) != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
if (pthread_join(t1, NULL) != 0) {
perror("pthread_join");
exit(EXIT_FAILURE);
}
if (pthread_join(t2, NULL) != 0) {
perror("pthread_join");
exit(EXIT_FAILURE);
}
return 0;
}
```
在上面的程序中,我们定义了两个函数 `print_even` 和 `print_odd`,分别用于打印偶数和奇数。然后在主函数中,我们创建了两个线程 `t1` 和 `t2`,分别执行 `print_even` 和 `print_odd` 函数。在创建线程时,我们调用了 `pthread_create` 函数,它接受四个参数:线程 ID、线程属性、线程函数、线程函数的参数。如果创建线程成功,`pthread_create` 函数返回 0,否则返回一个非零的错误码。
在两个线程都执行完毕后,我们调用了 `pthread_join` 函数,它会阻塞当前线程,直到指定的线程执行完毕。在本例中,我们阻塞了主线程,直到 `t1` 和 `t2` 线程都执行完毕。如果 `pthread_join` 函数调用成功,它会返回 0,否则返回一个非零的错误码。