2017-10-18 91 views
0

我有三个整数(A,B和C),我想创建两个线程(POSIX 的pthreads)来访问他们在这个特定的顺序,以保持结果一致:如何制作一个可以继续执行的pthread信号?

Thread 1 | Thread 2 
--------------------- 
a=1   b=5 
c=7 
      c=c+10 
      b=a+c*2 
a=b+b*10 

那是,thread2中的c = c + 10必须等到thread1中的c = 7完成。此外,thread1中的a = b + b * 10必须等到thread2中的b = a + c * 2完成。

我一直在使用互斥试过,但我打算(下面的代码)这是行不通的。如果thread2首先启动,它可以在thread1锁定它之前锁定mutex1,因此排序会丢失。锁定主线程中的互斥锁不是一种选择,因为它会产生未定义的行为(互斥锁被另一个线程锁定然后解锁)。我也试过使用条件变量,但也出现了类似的问题:信号可能发生在关联的等待之前。

#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?提前致谢。

+0

不应这些'的INT A,b,C;'变量是易失性? – Gaurav

+0

@usr我在这里简单的代码,真正的代码有并行 –

+0

执行看也不看深度更大的块,2个互斥一个同步作业似乎腥。 – spectras

回答

0
pthread_mutex_t mutex1, mutex2 = PTHREAD_MUTEX_INITIALIZER 

只初始化第二个;但这是一个不争的事实。根据您正在运行的系统,您可能没有注意到这一点,因为互斥量1未初始化,因此其上的操作可能失败,或者初始化参数常量可能为零...

信号/等待问题不是一个问题 - 你等候由一个互斥保护的条件下,这种模式:

lock(); 
while (check() == false) { 
    wait(); 
} 
func(); 
signal(); 
unlock(); 

所以线程1的检查将是真实的,FUNC将为c = 7 而线程2的检查是(C == 7 )和FUNC将为c + = 10