一、互斥量(互斥锁) 将输出作为共享资源,加锁,进行父线程输出大写HELLO WORLD,子线程输出小写hello world,利用随机数,使得睡眠时间,模拟线程占用cpu时间, 调用pthread_mutex_init初始
一、互斥量(互斥锁)
将输出作为共享资源,加锁,进行父线程输出大写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;
}
【文章原创作者:美国站群多ip服务器 http://www.558idc.com/mgzq.html