C语言I/O请使用互斥锁和信号量分别实现5个线程之间的同步
1.代码运行结果:
2.源码解析:
使用互斥锁: pthread_mutex_t mutex;:定义一个互斥锁。 pthread_mutex_init(&mutex, NULL);:初始化互斥锁。 pthread_mutex_lock(&mutex);:在临界区前加锁,确保同一时间只有一个线程可以进入临界区。 pthread_mutex_unlock(&mutex);:在临界区后解锁,允许其他线程进入临界区。 pthread_mutex_destroy(&mutex);:销毁互斥锁。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
// 互斥锁
pthread_mutex_t mutex;
void* thread_function(void* arg) {
int thread_id = *(int*)arg;
// 加锁
pthread_mutex_lock(&mutex);
printf("线程 %d 正在执行\n", thread_id);
// 模拟一些工作
for (int i = 0; i < 1000000; i++);
printf("线程 %d 执行完毕\n", thread_id);
// 解锁
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
// 初始化互斥锁
pthread_mutex_init(&mutex, NULL);
for (int i = 0; i < NUM_THREADS; i++) {
thread_args[i] = i;
pthread_create(&threads[i], NULL, thread_function, &thread_args[i]);
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
// 销毁互斥锁
pthread_mutex_destroy(&mutex);
return 0;
}
使用信号量: sem_t semaphore;:定义一个信号量。 sem_init(&semaphore, 0, 1);:初始化信号量,初始值为1,表示资源可用。 sem_wait(&semaphore);:等待信号量,如果信号量的值大于0,则减1并继续执行;如果信号量的值为0,则阻塞等待。 sem_post(&semaphore);:释放信号量,信号量的值加1,唤醒等待的线程。 sem_destroy(&semaphore);:销毁信号量。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_THREADS 5
// 信号量
sem_t semaphore;
void* thread_function(void* arg) {
int thread_id = *(int*)arg;
// 等待信号量
sem_wait(&semaphore);
printf("线程 %d 正在执行\n", thread_id);
// 模拟一些工作
for (int i = 0; i < 1000000; i++);
printf("线程 %d 执行完毕\n", thread_id);
// 释放信号量
sem_post(&semaphore);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
pthread_t threads[NUM_THREADS];
int thread_args[NUM_THREADS];
// 初始化信号量,初始值为1
sem_init(&semaphore, 0, 1);
for (int i = 0; i < NUM_THREADS; i++) {
thread_args[i] = i;
pthread_create(&threads[i], NULL, thread_function, &thread_args[i]);
}
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
// 销毁信号量
sem_destroy(&semaphore);
return 0;
}