-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathpthread_rwlock_t2.cpp
More file actions
74 lines (65 loc) · 1.57 KB
/
pthread_rwlock_t2.cpp
File metadata and controls
74 lines (65 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/***
* @Author: wujing
* @Date: 2021-02-24 04:09:44
* @LastEditTime: 2021-05-12 18:21:45
* @LastEditors: wujing
* @Description:
* @FilePath: /CPlusPlusProject/pthread/sync/pthread_rwlock_t2.cpp
* @可以输入预定的版权声明、个性签名、空行等
*/
#include <iostream>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
using namespace std;
int num = 5;
pthread_rwlock_t rwlock;
void *reader(void *arg)
{
pthread_rwlock_tryrdlock(&rwlock);
cout << "reader " << (long)arg << " got the lock" << endl;
pthread_rwlock_unlock(&rwlock);
return 0;
}
void *writer(void *arg)
{
pthread_rwlock_trywrlock(&rwlock);
cout << "writer " << (long)arg << " got the lock" << endl;
pthread_rwlock_unlock(&rwlock);
return 0;
}
int main()
{
int flag;
long n = 1, m = 1;
pthread_t wid, rid;
pthread_attr_t attr;
flag = pthread_rwlock_init(&rwlock, NULL);
if (flag)
{
cout << "rwlock init error" << endl;
return flag;
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); //thread sepatate
for (int i = 0; i < num; i++)
{
if (i % 3)
{
pthread_create(&rid, &attr, reader, (void *)n);
cout << "create reader " << n << endl;
n++;
}
else
{
pthread_create(&wid, &attr, writer, (void *)m);
cout << "create writer " << m << endl;
m++;
}
}
sleep(5); //wait other done
return 0;
}