一.用代码实现多线程
#include<stdio.h>
#include<pthread.h>
void* start_routine(void* val)
{
// int count=5000;
// int i=0;
while(count)
{
sleep(1);
printf("I am a new thread:tid:%lu,pid:%d\n" , pthread_self(),getpid());
}
}
int main()
{
pthread_t tid1,tid2,tid3,tid4;
pthread_create(&tid1,NULL,*start_routine,NULL);
pthread_create(&tid2,NULL,*start_routine,NULL);
pthread_create(&tid3,NULL,*start_routine,NULL);
pthread_create(&tid4,NULL,*start_routine,NULL);
while(1)
{
sleep(1);
printf("I am a main thread:tid:%lu pid:%d\n",pthread_self(),getpid());
}
return 0;
}
运行结果图:
二.同步与互斥的概念
- 多个线程同时访问共享数据时可能会发生冲突,例如:两个线程都要对某个全局变量进行加一操作,这个操作在某个平台下需要三条指令完成:
1.从内存中读变量值到寄存器中。
2.寄存器的值加一。
3.将寄存器的值协会内存。
若有的线程在执行此操作的时候,刚执行了第一条,被切了出去,则会导致有的变量只加了一次,而非两次。
例如下边的示例
#include<stdio.h>
#include<pthread.h>
static int count=0;
void* start_routine(void* val)
{
int t=5000;
while(t)
{
int val=0;
val=count;
printf("%d\n",count);
t--;
count=val+1;
}
return NULL;
}
int main()
{
void* val=NULL;
pthread_t tid1,tid2,tid3,tid4;
pthread_create(&tid1,NULL,*start_routine,NULL);
pthread_create(&tid2,NULL,*start_routine,NULL);
pthread_create(&tid3,NULL,*start_routine,NULL);
pthread_create(&tid4,NULL,*start_routine,NULL);
//while(1)
// {
// sleep(1);
// printf("I am a main thread:tid:%lu pid:%d\n",pthread_self(),getpid());
pthread_join(tid1,&val);
pthread_join(tid2,&val);
pthread_join(tid3,&val);
pthread_join(tid4,&val);
printf("%d\n",count);
// }
return 0;
}
本来期望的结果是20000;
但实际结果如下几个图:
结果一次跟一次均不一样。导致其结果的原因就是多个线程非原子性的访问临界资源,而导致临界资源被修改。此处解决的办法就是引入互斥锁。
三.用代码实现互斥锁
#include<stdio.h>
#include<pthread.h>
static int count=0;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
void* start_routine(void* val)
{
int t=5000;
while(t)
{
pthread_mutex_lock(&lock);
int val=0;
val=count;
printf("%d\n",count);
t--;
count=val+1;
pthread_mutex_unlock(&lock);
}
return NULL;
}
运行结果为:
结果是我们期望的20000.