进程的同步与互斥代码
时间: 2023-10-10 12:15:43 浏览: 50
进程同步和互斥是多进程编程中非常重要的概念,下面是一个简单的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_t tid[2];
int counter;
void* thread1(void* arg)
{
int i;
for(i = 0; i < 5; i++)
{
counter++;
printf("Thread 1: Counter = %d\n", counter);
usleep(1);
}
}
void* thread2(void* arg)
{
int i;
for(i = 0; i < 5; i++)
{
counter--;
printf("Thread 2: Counter = %d\n", counter);
usleep(1);
}
}
int main(void)
{
int i = 0;
int err;
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &thread1, NULL);
if (err != 0)
printf("Can't create thread :[%s]", strerror(err));
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}
```
这段代码创建了两个线程,每个线程都执行了一个简单的循环,循环内对共享变量 counter 进行加减操作,并输出结果。由于两个线程都对共享变量进行读写,因此会出现数据不一致的问题。
为了解决这个问题,我们需要使用线程同步和互斥机制。下面是一个修改后的代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
void* thread1(void* arg)
{
int i;
for(i = 0; i < 5; i++)
{
pthread_mutex_lock(&lock);
counter++;
printf("Thread 1: Counter = %d\n", counter);
pthread_mutex_unlock(&lock);
usleep(1);
}
}
void* thread2(void* arg)
{
int i;
for(i = 0; i < 5; i++)
{
pthread_mutex_lock(&lock);
counter--;
printf("Thread 2: Counter = %d\n", counter);
pthread_mutex_unlock(&lock);
usleep(1);
}
}
int main(void)
{
int i = 0;
int err;
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("Mutex init failed\n");
return 1;
}
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &thread1, NULL);
if (err != 0)
printf("Can't create thread :[%s]", strerror(err));
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock);
return 0;
}
```
在修改后的代码中,我们增加了一个互斥锁,每当线程要对共享变量进行读写时,需要先获取锁,然后执行操作,最后释放锁。这样可以保证同一时刻只有一个线程可以对共享变量进行操作,从而避免了数据不一致的问题。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)