1+ #include < stdio.h>
2+ #include < stdlib.h>
3+ #include < unistd.h>
4+ #include < pthread.h>
5+
6+ pthread_spinlock_t spin_lock;
7+
8+ int key = 0 ;
9+
10+ // 临界资源
11+ int nums = 0 ;
12+
13+ // 生产者
14+ void *producer (void *) {
15+ int times = 10000000 ;
16+ if (key == 1 ) {
17+ while (times--) {
18+ pthread_spin_lock (&spin_lock);
19+ nums ++;
20+ pthread_spin_unlock (&spin_lock);
21+ }
22+ } else if (key == 0 ) {
23+ while (times--) {
24+ nums ++;
25+ }
26+ }
27+ }
28+
29+ // 消费者
30+ void *comsumer (void *) {
31+ int times = 10000000 ;
32+ if (key == 1 ) {
33+ while (times--) {
34+ pthread_spin_lock (&spin_lock);
35+ nums --;
36+ pthread_spin_unlock (&spin_lock);
37+ }
38+ } else if (key == 0 ) {
39+ while (times--) {
40+ nums --;
41+ }
42+ }
43+ }
44+
45+ int main () {
46+ printf (" ================= option =================\n " );
47+ printf (" Add spin_lock, please input 1\n " );
48+ printf (" Don't add spin_lock, please input 0\n " );
49+ printf (" ==========================================\n\n " );
50+ printf (" Please input your option: " );
51+ scanf (" %d" , &key);
52+ if (key != 0 && key != 1 ) {
53+ printf (" Input error, please input 1 or 0\n " );
54+ return 0 ;
55+ }
56+ pthread_spin_init (&spin_lock, 0 );
57+ printf (" Start in main function: num.\n " );
58+ pthread_t thread1, thread2;
59+ pthread_create ( &thread1, NULL , &producer, NULL );
60+ pthread_create ( &thread2, NULL , &comsumer, NULL );
61+ pthread_join (thread1, NULL );
62+ pthread_join (thread2, NULL );
63+ printf (" Print in main function: num = %d" , nums);
64+ return 0 ;
65+ }
0 commit comments