2013-07-09 74 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完成。

這是我對這個問題的看法。