- 论坛徽章:
- 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);
- }
复制代码 我要模拟的情况是有一个test线程阻塞在pthread_cond_wait(&cond,&mtx);,另外一个add线程阻塞在pthread_mutex_lock(&mtx);
然后主线程调用pthread_cond_signal(&cond);和pthread_mutex_unlock(&mtx); 这个时候会是哪个线程抢到锁?
pthread_cond_wait的线程会高优先级抢到锁吗,还是说随机的?
我上面测试代码是add线程抢到了锁。
我的测试代码输出:
test before lock
main begin
add before lock
signal over before unlock
###6
@@@@@6 |
|