- 论坛徽章:
- 0
|
才学习多线程读写锁。
参照网上的教程,自己写了简单的例子,但是写线程一直都未进入,高手帮忙看一下我哪里错了,谢谢!- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <iostream>
- using namespace std;
- int g_count = 0;
- pthread_rwlock_t rwlock;
- void * thd_func_read_1(void * arg)
- {
- while(1)
- {
- pthread_rwlock_rdlock(&rwlock);
- sleep(1);
- cout<<"read1 count:"<<g_count<<endl;
- pthread_rwlock_unlock(&rwlock);
- }
- return NULL;
- }
- void * thd_func_read_2(void * arg)
- {
- while(1)
- {
- pthread_rwlock_rdlock(&rwlock);
- sleep(1);
- cout<<"read2 count:"<<g_count<<endl;
- pthread_rwlock_unlock(&rwlock);
- }
- return NULL;
- }
- void * thd_func_write(void * arg)
- {
- while(1)
- {
- pthread_rwlock_wrlock(&rwlock);
- sleep(1);
- cout<<"write count:"<<++g_count<<endl;
- if( g_count >= 5 )
- {
- pthread_rwlock_unlock(&rwlock);
- pthread_exit(0);
- return NULL;
- }
- pthread_rwlock_unlock(&rwlock);
- }
- return NULL;
- }
- int main(int argc, char **argv)
- {
- int ret;
- pthread_t thd_read_1, thd_read_2, thd_write;
- pthread_rwlock_init(&rwlock, NULL);
- ret = pthread_create(&thd_read_1, NULL, thd_func_read_1, NULL); //创建线程1
- if(ret){
- perror("thd_read_1:\n");
- return 1;
- }
- ret = pthread_create(&thd_read_2, NULL, thd_func_read_2, NULL); //创建线程2
- if(ret){
- perror("thd_read_2: \n");
- return 1;
- }
- ret = pthread_create(&thd_write, NULL, thd_func_write, NULL); //创建线程2
- if(ret){
- perror("thd_read_3: \n");
- return 1;
- }
- pthread_join(thd_read_1,NULL);
- pthread_join(thd_read_2,NULL);
- pthread_join(thd_write,NULL);
- return 0;
- }
复制代码 输出的内容也很奇怪:
read2 count:read1 count:00
read1 count:read2 count:00
read1 count:read2 count:00
read1 count:0
read2 count:0
read2 count:0
read1 count:0
read1 count:read2 count:00
read1 count:read2 count:00
read1 count:0
read2 count:0
read2 count:read1 count:00
|
|