c - 如何让一个线程等待其他线程完成

标签 c multithreading

我有一个程序,我在其中创建了两个线程。在一个线程中,我为整数 ab 分配了一个值。在第二个线程中,我想访问 ab,以更改它们的值。

#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()
  2. 当第一个线程完成时,使用条件变量向第二个线程发出信号。
  3. 停止使用线程,因为让一个线程的唯一工作就是等待另一个线程是没有意义的。只需将逻辑按顺序放在一个线程中即可。

关于c - 如何让一个线程等待其他线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17548455/

相关文章:

c - strcmp() 用于文件中的行

c - while (*next != NULL) 当指针为 NULL 时循环不退出

c - 如何使用 FFI 从 C 调用 Rust 结构的方法?

c++ - Win32 重置事件,如带有 boost C++ 的同步类

用于同时 ping 多台主机的 Linux Bash 脚本

java - 初学者关于Java多线程的问题以及synchronized block 和wait()/notify()的使用

c - 使用加速度计数据进行 FFT

c - 将可执行文件命名为c

java - 在 Swing 中没有得到预期的输出

c++ - 在 Openmp (C++) 中销毁线程