我有兩個執行緒和一個 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.
}
uj5u.com熱心網友回復:
為此,忙回圈效率低下。你想要的是一個條件,一個互斥體和一個簡單的計數器:
- 鎖定互斥鎖。
- 增加計數器。
- 如果計數器為
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371830.html
上一篇:專案機子,當虛擬執行緒進行阻塞系統呼叫時會發生什么?
下一篇:如何將常量佇列傳遞給函式?
