2013-07-09 75 views
0

我有一个程序,我创建了两个线程。在一个线程中,我为整数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(分配),以完成并退出。我如何实现它?

+1

请参阅[pthread_join](http://man7.org/linux/man-pages/man3/pthread_join.3.html)。 –

+0

如果你不打算使用它,在初始化,配置和销毁'attr'时没有意义。 – pilcrow

回答

9

如果一个线程必须等待对方说完,我看到三个选项:

  1. 使第二个线程的第一个做pthread_join()
  2. 使用条件变量在第一个线程完成时发信号通知第二个线程。
  3. 停止使用线程,因为没有意义的是让一个人的唯一工作是等待另一个人。只需将逻辑按顺序放入单个线程即可。
+3

3.是最好的答案。 :-) –

+0

@JamesMcLaughlin:在没有其他信息的情况下,这肯定是我的选择。 –

+0

我想我应该去1或2 ...嗯,我只是想了解更多关于线程,并在这种情况下发生..谢谢你的建议。 –

0

我建议你使用信号量。

  1. 定义与价值全球信号灯1.

  2. 之前创建两个线程,你做一个P动作和信号量的值为0

  3. 在线程1后你已经分配了a和b的值,你做了一个V操作。信号值将为1.

  4. 在执行打印之前,在线程2中添加一个操作V.如果线程1尚未完成任务,线程2将进入休眠状态,直到线程1完成。

这是我对这个问题的看法。