在多线程中对共享资源的访问
在一个多线程的程序中,有时需要同时对共享资源的访问,就会造成对共享资源的读写问题。
例如:有五个线程,其中一个对共享资源进行修改,其余四个线程需要同时对共享资源进行读访问。势必会造成其余四个线程读取数据的不稳定。此时就可以使用互斥锁去解决这一问题。
当修改共享资源的线程需要对数据进行修改时,首先得到互斥锁,进行加锁。其他进程就被阻塞不可以去读取资源了。操作完成后,解锁,其他线程就可以对资源进行访问了。
关于互斥锁的操作有以下步骤:
1、初始化互斥锁
pthread_mutex_init(&mutex,NULL);
2、对操作的数据加锁
pthread_mutex_lock(&mutex); “`
3、对操作的数据解锁
pthread_mutex_unlock(&mutex);
4、销毁互斥锁
pthread_mutex__destroy(&mutex); “
`
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//目的创建多个线程,一个对共享资源进行修改,四个对共享资源进行访问
#if 0
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
int pthread_join(pthread_t thread, void **retval);
#endif
char name[] = "hello,world!";
pthread_mutex_t mutex;
void *start_routine_read(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
printf("@%d,%s\n",pthread_self(),name);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return (void *)0;
}
void *start_routine_write(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
char temp_str[12] = "";
printf("input string:");
scanf("%s",temp_str);
strcpy(name,temp_str);
printf("@%d,write data:%s\n",pthread_self(),name);
pthread_mutex_unlock(&mutex);
sleep(1);
}
return (void *)0;
}
int main(void)
{
pthread_t thread[5];
int i = 0;
pthread_mutex_init(&mutex,NULL);
//创建5个线程
for(i = 1;i < 5;i++)
{
pthread_create(thread+i,NULL,start_routine_read,NULL);
}
pthread_create(thread,NULL,start_routine_write,NULL);
while(1);
pthread_mutex_destroy(&mutex);
//回收线程资源
for(i = 1;i < 5;i++)
{
pthread_join(thread[i],NULL);
}
pthread_join(thread[0],NULL);
return 0;
}
代码中尚有不完善指出,请指出,谢谢!