要确保只有一个线程通过临界区,可以使用以下几种方法:
import threading
# 创建锁对象
lock = threading.Lock()
def critical_section():
# 获取锁
lock.acquire()
# 临界区代码
# ...
# 释放锁
lock.release()
# 创建多个线程
threads = []
for _ in range(10):
t = threading.Thread(target=critical_section)
threads.append(t)
t.start()
# 等待所有线程完成
for t in threads:
t.join()
#include
#include
// 创建互斥量对象
pthread_mutex_t mutex;
void* critical_section(void* arg){
// 获取互斥量
pthread_mutex_lock(&mutex);
// 临界区代码
// ...
// 释放互斥量
pthread_mutex_unlock(&mutex);
}
int main(){
// 初始化互斥量
pthread_mutex_init(&mutex, NULL);
// 创建多个线程
pthread_t threads[10];
for(int i = 0; i < 10; i++){
pthread_create(&threads[i], NULL, critical_section, NULL);
}
// 等待所有线程完成
for(int i = 0; i < 10; i++){
pthread_join(threads[i], NULL);
}
// 销毁互斥量
pthread_mutex_destroy(&mutex);
return 0;
}
#include
#include
#include
// 创建信号量对象
sem_t semaphore;
void* critical_section(void* arg){
// 等待信号量的值为1
sem_wait(&semaphore);
// 临界区代码
// ...
// 释放信号量,将其值设置为1
sem_post(&semaphore);
}
int main(){
// 初始化信号量,将其值设置为1
sem_init(&semaphore, 0, 1);
// 创建多个线程
pthread_t threads[10];
for(int i = 0; i < 10; i++){
pthread_create(&threads[i], NULL, critical_section, NULL);
}
// 等待所有线程完成
for(int i = 0; i < 10; i++){
pthread_join(threads[i], NULL);
}
// 销毁信号量
sem_destroy(&semaphore);
return 0;
}
以上是几种常见的解决并发问题的方法,具体使用哪种方法取决于编程语言和操作系统的支持和约束。
上一篇:并发问题(死锁?)