互斥体(Mutex):
信号量(Semaphore):
互斥体的优势:
信号量的优势:
互斥体:
信号量:
互斥体:
信号量:
互斥体相关问题:
信号量相关问题:
互斥体示例(C语言):
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int shared_data = 0;
void* thread_func(void* arg) {
pthread_mutex_lock(&mutex);
shared_data++;
printf("Shared data: %d
", shared_data);
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t threads[10];
for (int i = 0; i < 10; i++) {
pthread_create(&threads[i], NULL, thread_func, NULL);
}
for (int i = 0; i < 10; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
信号量示例(C语言):
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
sem_t sem = SEM_INITIALIZER(1); // 初始化信号量为1
int shared_data = 0;
void* thread_func(void* arg) {
sem_wait(&sem);
shared_data++;
printf("Shared data: %d
", shared_data);
sem_post(&sem);
return NULL;
}
int main() {
pthread_t threads[10];
for (int i = 0; i < 10; i++) {
pthread_create(&threads[i], NULL, thread_func, NULL);
}
for (int i = 0; i < 10; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
通过以上示例代码,可以看到互斥体和信号量在多线程编程中的应用及其基本操作。
领取专属 10元无门槛券
手把手带您无忧上云