一、互斥量(互斥鎖)
將輸出作爲共享資源,加鎖,進行父線程輸出大寫HELLO WORLD,子線程輸出小寫hello world,利用隨機數,使得睡眠時間,模擬線程佔用cpu時間,
調用pthread_mutex_init初始化的互斥鎖,在釋放內存前需要調用pthread_mutex_destroy
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
pthread_mutex_t mutex; //鎖的定義
void *tfn(void *arg)
{
srand(time(NULL));
while(1){
pthread_mutex_lock(&mutex);
printf("hello");
sleep(rand() % 3); /*模擬長時間操作共享資源,導致cpu易主,產生與時間>有關的錯誤*/
printf("world\n");
pthread_mutex_unlock(&mutex);
sleep(rand() % 3);
}
return NULL;
}
int main(void)
{
pthread_t tid;
srand(time(NULL));
pthread_mutex_init(&mutex,NULL); //mutex == 1
pthread_create(&tid,NULL,tfn,NULL);
while(1){
pthread_mutex_lock(&mutex);
printf("HELLO");
sleep(rand()%3);
printf("WORLD\n");
pthread_mutex_unlock(&mutex);
//將 unlock 挪至第二個 sleep 後,發現交替現象很難出現。
//線程在操作完共享資源後本應該立即解鎖,但修改後,線程抱着鎖睡眠。睡醒解鎖後又立即加鎖,這將導致其他線程很難搶到鎖
sleep(rand() % 3);
}
pthread_mutex_destroy(&mutex);
}
二、讀寫鎖,同時多個進程多共享數據進行讀寫操作,,讀共享,寫獨佔,讀寫並行阻塞是,寫的優先級高
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
int counter; //全局資源
pthread_rwlock_t rwlock;
void *th_write(void *arg) //寫線程
{
int t;
int i = (int)arg;
while(1){
t = counter;
usleep(1000);
pthread_rwlock_wrlock(&rwlock);
printf("========write %d: %lu: counter=%d ++counter=%d\n",i,pthread_self(),t,++counter);
pthread_rwlock_unlock(&rwlock);
usleep(5000);
}
return NULL;
}
void *th_read(void *arg)
{
int i = (int)arg;
while(1){
pthread_rwlock_rdlock(&rwlock);
printf("---------read %d: %lu: %d\n",i,pthread_self(),counter);
pthread_rwlock_unlock(&rwlock);
usleep(900);
}
return NULL;
}
int main(void)
{
int i;
pthread_t tid[8];
pthread_rwlock_init(&rwlock,NULL);
for(i = 0; i < 3; i++)
pthread_create(&tid[i],NULL,th_write,(void *)i);
for(i = 0; i < 5; i++)
pthread_create(&tid[i+3],NULL,th_read,(void *)i);
//三個寫線程,5個讀線程
for(i = 0; i < 8; i++)
pthread_join(tid[i],NULL);
pthread_rwlock_destroy(&rwlock); //釋放讀寫鎖
return 0;
}