在c中,如何让线程等待其他线程完成

Pra*_*dar 0 c multithreading

我有一个程序,我创建了两个线程.在一个线程中,我为整数a和b分配了一个值.在第二个线程中,我想访问a和b,以更改其值.

#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;
}
Run Code Online (Sandbox Code Playgroud)

但是上面的程序同时执行两个线程.有时我会

thread1..
The value of a and b is: 3, 3
thread 2
Value of a and b is: 1, 1
Run Code Online (Sandbox Code Playgroud)

有时候我会

thread 2
Value of a and b is: -1, -1
You are now in thread1..
The value of a and b is: 3, 3
Run Code Online (Sandbox Code Playgroud)

我想让thread-2(add)等待thread-1(assign)完成并退出.我该如何实现它?

Joh*_*nck 10

如果一个线程必须等待另一个线程完成,我会看到三个选项:

  1. 使第二个线程pthread_join()在第一个线程上执行.
  2. 使用条件变量在第一个线程完成时发出第二个线程的信号.
  3. 停止使用线程,因为拥有一个唯一的工作就是等待另一个线程是毫无意义的.只需将逻辑顺序放在一个线程中.

  • 3.是最好的答案.:-) (3认同)
  • @JohnZwinck - 重要的是要记住,人们发布的许多代码示例都是他们的问题是学术练习,旨在消除所有多余的素材围绕他们的问题的核心,或者他们正在这样做是因为他们试图尝试他们几乎没有经验的东西.告诉别人他们的问题是错误的往往是错误的答案. (2认同)