我正在尝试对2个进程进行严格的更改,但我不确定如何声明关键区域和非关键区域。这是我的代码:
#include <iostream>
#include <pthread.h>
int count;
int turn = 0; // Shared variable used to implement strict alternation
void* myFunction(void* arg)
{
int actual_arg = *((int*) arg);
for(unsigned int i = 0; i < 10; ++i) {
while(1)
{
while(turn != 0)
{
critical_region_0();
turn = 1;
non_critical_region_0();
}
}
// Beginning of the critical region
count++;
std::cout << "Thread #" << actual_arg << " count = " << count <<
std::endl;
// End of the critical region
while(0)
{
while(turn != 1)
{
critical_region_1();
turn = 0
non_critical_region_1();
}
}
}
pthread_exit(NULL);
}
int main()
{
int rc[2];
pthread_t ids[2];
int args[2];
count = 0;
for(unsigned int i = 0; i < 2; ++i) {
args[i] = i;
rc[i] = pthread_create(&ids[i], NULL, myFunction, (void*) &args[i]);
}
for(unsigned int i = 0; i < 2; ++i) {
pthread_join(ids[i], NULL);
}
std::cout << "Final count = " << count << std::endl;
pthread_exit(NULL);
}
我知道关键区域和非关键区域被编写为好像它们是一种方法,但我将它们用作占位符。有没有办法在不使用这些方法的情况下进行严格交替?
输出应该是什么样的。
Thread #0 count = 1
Thread #1 count = 2
Thread #0 count = 3
Thread #1 count = 4
Thread #0 count = 5
Thread #1 count = 6
Thread #0 count = 7
Thread #1 count = 8
Thread #0 count = 9
Thread #1 count = 10
Thread #0 count = 11
Thread #1 count = 12
Thread #0 count = 13
Thread #1 count = 14
Thread #0 count = 15
Thread #1 count = 16
Thread #0 count = 17
Thread #1 count = 18
Thread #0 count = 19
Thread #1 count = 20
Final count = 20
我只能设法得到的输出是线程1,然后是线程0。
答案 0 :(得分:0)
我认为这是信号的经典之处。控制线程的每个函数看起来都像(例如,线程1)
while( ... ) {
...
pthread_cond_signal(thread1_done_work);
pthread_cond_wait(thread_2_done_work);
}
其中两个工作变量都是pthread_cond_t
类型的全局变量 - 我认为它有两个更具可读性,但你不必使用两个(考虑到互斥体实现)。
线程2一启动就需要等待条件。以下是一些细节:
https://linux.die.net/man/3/pthread_cond_wait
https://linux.die.net/man/3/pthread_cond_signal
基本上每个线程都会发出信号(这会阻塞,直到另一个线程准备好捕获它),然后等待另一个线程。所以他们会谈论&#34;轮到你,轮到你了。如果你坚持为两个线程使用相同的功能,你可以将条件变量作为参数调整(相对于1交换线程2)。
最后一个小注 - 这有点与线程的整个目的相矛盾。