- 論壇徽章:
- 2
|
- #include<pthread.h>
- #include<unistd.h>
- #include<stdio.h>
- #include<string.h>
- #include<stdlib.h>
- #include<time.h>
- static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
- static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
- int global_val = 0;
- void* test(void *argv) {
- printf("test before lock\n");
- pthread_mutex_lock(&mtx);
- while(global_val == 0) {
- pthread_cond_wait(&cond,&mtx);
- }
- pthread_mutex_unlock(&mtx);
- printf("@@@@@%d\n",global_val);
- }
- void* add(void *argv) {
- sleep(1);
- printf("add before lock\n");
- pthread_mutex_lock(&mtx);
- global_val++;
- printf("###%d\n",global_val);
- pthread_mutex_unlock(&mtx);
-
- }
- int main() {
- pthread_t tid1,tid2;
- global_val = 0;
- pthread_create(&tid1,NULL,test,NULL);
- sleep(1);
- pthread_create(&tid2,NULL,add,NULL);
- printf("main begin\n");
- pthread_mutex_lock(&mtx);
- global_val = 5;
- sleep(3);
- pthread_cond_signal(&cond);
- printf("signal over before unlock\n");
- sleep(3);
- pthread_mutex_unlock(&mtx);
- pthread_join(tid1,NULL);
- pthread_join(tid2,NULL);
- }
復(fù)制代碼 我要模擬的情況是有一個(gè)test線程阻塞在pthread_cond_wait(&cond,&mtx);,另外一個(gè)add線程阻塞在pthread_mutex_lock(&mtx);
然后主線程調(diào)用pthread_cond_signal(&cond);和pthread_mutex_unlock(&mtx); 這個(gè)時(shí)候會是哪個(gè)線程搶到鎖?
pthread_cond_wait的線程會高優(yōu)先級搶到鎖嗎,還是說隨機(jī)的?
我上面測試代碼是add線程搶到了鎖。
我的測試代碼輸出:
test before lock
main begin
add before lock
signal over before unlock
###6
@@@@@6 |
|