[英]How can I synchronize two CPU threads in a Specific line of two threads?
我有兩個線程和一個 CPU。
我希望在他們的程序中較早到達 A 行的兩個線程中的每一個都等待另一個線程到達 A 行,之后兩個線程繼續運行他們的程序。 我已按如下方式完成此操作,但我希望 A 行的兩個線程同時運行它們的程序。
我怎樣才能做到這一點?
我的代碼:
//headers
static volatile bool waitFlag[2];
void *threadZero(void*){
//some codes
waitFlag[1] = true;
while(!waitFlag[0]);
//line A of thread zero
//some codes
}
void *threadOne(void*){
// some codes
waitFlag[0] = true;
while(!waitFlag[1]);
//line A of thread one
//some codes
}
int main(){
waitFlag[0] = waitFlag[1] = false;
//Creates two threads and waits for them to finish.
}
為此目的,繁忙的循環是低效的。 你想要的是一個條件,一個互斥鎖和一個簡單的計數器:
2
,則按條件廣播。通過更改計數器的閾值,這個邏輯可以很容易地適應任何數量的線程。 最后一個增加計數器的線程(受互斥鎖保護)將在條件下廣播,並將同時解鎖自己和所有其他線程。 如果您想多次同步,您也可以重置計數器。
這是一個例子:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/random.h>
pthread_cond_t cond;
pthread_mutex_t cond_mutex;
unsigned int waiting;
// Sleep a random amount between 0 and 3s.
// This is just for testing, you don't actually neeed it.
void waste_time(void) {
unsigned us;
getrandom(&us, sizeof(us), 0);
us %= 3000000;
fprintf(stderr, "[%lx] Sleeping %u us...\n", pthread_self(), us);
usleep(us);
}
void synchronize(void) {
pthread_mutex_lock(&cond_mutex);
if (++waiting == 2) {
pthread_cond_broadcast(&cond);
} else {
while (waiting != 2)
pthread_cond_wait(&cond, &cond_mutex);
}
pthread_mutex_unlock(&cond_mutex);
}
void *threadZero(void *_) {
waste_time();
// ...
synchronize();
fprintf(stderr, "[%lx] Resuming.\n", pthread_self());
// ...
return NULL;
}
void *threadOne(void *_) {
waste_time();
// ...
synchronize();
fprintf(stderr, "[%lx] Resuming.\n", pthread_self());
// ...
return NULL;
}
int main(void) {
pthread_t zero, one;
pthread_create(&zero, NULL, threadZero, NULL);
pthread_create(&one, NULL, threadOne, NULL);
// ...
pthread_join(zero, NULL);
pthread_join(one, NULL);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.