线程同步2操作系统实验
时间: 2023-11-28 20:42:29 浏览: 59
在多任务操作系统环境下,进程和线程的同步控制是多线程和多进程编程的一个重点。其中,线程同步是指多个线程在执行过程中需要访问共享资源时,保证每个线程都能按照一定的顺序访问共享资源,避免出现数据不一致或者其他问题。常见的线程同步方式包括临界区、互斥量、信号量等。
临界区是线程同步的一种方式,即它在同一时刻只允许一个线程进入,其他线程只能等待。在进入临界区之前,需要获取一个锁,执行完临界区代码后再释放锁。这样可以保证在同一时刻只有一个线程在执行临界区代码,避免出现数据竞争等问题。
下面是一个示例代码,其中包括两个线程,一个写线程和一个读线程,它们共享一个数组A。写线程对数组进行10次写操作,每次写操作对A的每个元素赋一个相同的值;读线程对数组进行10次读操作,每次读操作输出A中所有元素的值。
```
#include <stdio.h>
#include <pthread.h>
#define THREAD_NUM 2
#define ARRAY_SIZE 10
int A[ARRAY_SIZE];
pthread_mutex_t mutex;
void *write_thread(void *arg) {
int i, j;
for (i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
for (j = 0; j < ARRAY_SIZE; j++) {
A[j] = i;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
void *read_thread(void *arg) {
int i, j;
for (i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
for (j = 0; j < ARRAY_SIZE; j++) {
printf("%d ", A[j]);
}
printf("\n");
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[THREAD_NUM];
pthread_mutex_init(&mutex, NULL);
pthread_create(&threads[0], NULL, write_thread, NULL);
pthread_create(&threads[1], NULL, read_thread, NULL);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
```
运行结果可能会出现数据不一致的情况,因为读线程和写线程没有进行同步。为了解决这个问题,可以使用互斥量来进行同步。修改后的代码如下:
```
#include <stdio.h>
#include <pthread.h>
#define THREAD_NUM 2
#define ARRAY_SIZE 10
int A[ARRAY_SIZE];
pthread_mutex_t mutex;
void *write_thread(void *arg) {
int i, j;
for (i = 0; i < 10; i++) {
for (j = 0; j < ARRAY_SIZE; j++) {
pthread_mutex_lock(&mutex);
A[j] = i;
pthread_mutex_unlock(&mutex);
}
}
pthread_exit(NULL);
}
void *read_thread(void *arg) {
int i, j;
for (i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
for (j = 0; j < ARRAY_SIZE; j++) {
printf("%d ", A[j]);
}
printf("\n");
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[THREAD_NUM];
pthread_mutex_init(&mutex, NULL);
pthread_create(&threads[0], NULL, write_thread, NULL);
pthread_create(&threads[1], NULL, read_thread, NULL);
pthread_join(threads[0], NULL);
pthread_join(threads[1], NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
```