我有一个程序,我创建了两个线程。在一个线程中,我为整数a和b赋值。在第二个线程中,我想访问a和b,以更改它们的值。在c中,如何使一个线程等待其他线程完成
#include <stdio.h>
#include <pthread.h>
struct data {
int a;
int b;
};
struct data temp;
void *assign(void *temp)
{
struct data *new;
new = (struct data *) temp;
new->a = 2;
new->b = 2;
printf("You are now in thread1..\n The value of a and b is: %d, %d", new->a + 1, new->b + 1);
printf("\n");
pthread_exit(NULL);
}
void *add(void *temp1)
{
struct data *new1;
new1 = (struct data *) temp1;
printf("You are now in thread 2\nValue of a and b is: %d, %d\n", new1->a - 1, new1->b - 1);
pthread_exit(NULL);
}
int main()
{
pthread_t threads[2];
pthread_attr_t attr;
void *status;
int rc, t;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], NULL, assign, (void *) &temp);
pthread_create(&threads[1], NULL, add, (void *) &temp);
pthread_attr_destroy(&attr);
for (t = 0; t < 2; t++) {
rc = pthread_join(threads[t], &status);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
printf("Main: completed join with thread %ld having a status of %ld\n", t, (long) status);
}
pthread_exit(NULL);
return 0;
}
但上述程序同时执行两个线程。有时我
thread1..
The value of a and b is: 3, 3
thread 2
Value of a and b is: 1, 1
,有时我得到
thread 2
Value of a and b is: -1, -1
You are now in thread1..
The value of a and b is: 3, 3
我要让线程2(添加)等待线程1(分配),以完成并退出。我如何实现它?
请参阅[pthread_join](http://man7.org/linux/man-pages/man3/pthread_join.3.html)。 –
如果你不打算使用它,在初始化,配置和销毁'attr'时没有意义。 – pilcrow