我有三个整数(a、b 和 c),我想创建两个线程(POSIX pthreads)来按此特定顺序访问它们,以保持结果一致:
Thread 1 | Thread 2
---------------------
a=1 b=5
c=7
c=c+10
b=a+c*2
a=b+b*10
也就是说,线程 2 中的 c=c+10 必须等待线程 1 中的 c=7 完成。另外,线程 1 中的 a=b+b*10 必须等待线程 2 中的 b=a+c*2 完成。
我尝试过使用互斥体,但它不能按我的预期工作(代码如下)。如果线程 2 先启动,它可以在线程 1 锁定互斥量 1 之前锁定它,因此顺序会丢失。从主线程锁定互斥锁不是一个选项,因为它会产生未定义的行为(互斥锁被不同的线程锁定然后解锁)。我也尝试过使用条件变量,但出现了类似的问题:信号可能在关联的等待之前发生。
#include <pthread.h>
#include <stdio.h>
int a, b, c;
pthread_mutex_t mutex1, mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *thread1(void *arg) {
pthread_mutex_lock(&mutex1);
a = 1;
c = 7;
pthread_mutex_unlock(&mutex1);
pthread_mutex_lock(&mutex2);
a = b + b*10;
pthread_exit(NULL);
}
void *thread2(void *arg) {
pthread_mutex_lock(&mutex2);
b = 5;
pthread_mutex_lock(&mutex1);
c = c + 10;
b = a + c*2;
pthread_mutex_unlock(&mutex2);
pthread_exit(NULL);
}
int main() {
pthread_t t1, t2;
if(pthread_create(&t1, NULL, thread1, NULL)) {
fprintf(stderr, "Error creating Thread 1\n");
return 0;
}
if(pthread_create(&t2, NULL, thread2, NULL)) {
fprintf(stderr, "Error creating Thread 2\n");
return 0;
}
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return a;
}
我的问题是,使用 pthreads 实现我想要的线程排序的正确方法是什么?提前致谢。
最佳答案
pthread_mutex_t mutex1, mutex2 = PTHREAD_MUTEX_INITIALIZER
仅初始化第二个;但这是小事一桩。根据您运行的系统,您可能不会注意到这一点,因为 mutex1 未初始化,因此对其的操作可能会失败,或者初始化常量可能为零......
信号/等待问题不是问题——您等待受互斥锁保护的条件,在这种模式中:
lock();
while (check() == false) {
wait();
}
func();
signal();
unlock();
因此 thread1 的检查将为 true,并且 func 将为 c = 7 而thread2的检查将是(c == 7)并且func将是c += 10
关于c - 如何让一个 pthread 向另一个 pthread 发出信号,表明它可以继续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46807586/