c - 为什么信号量不阻塞第二个线程?(C)
问题描述
我想编写一个简单的 C 程序来更好地理解信号量。有两个线程,它们都调用相同的函数。第一个,增加全局变量,第二个线程,减少全局变量。
我试图在第一个线程完成工作之前阻止第二个线程使用该函数。但我仍然得到错误的答案:-2000。看起来两个线程都有偏移量-1。我该如何解决这个问题,使输出始终为 0?我认为函数内部的 sem_wait 应该阻塞第二个线程,直到第一个线程结束。因此偏移量应该保持为 1。
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_LOOPS 1000
long long counter = 0;
sem_t sem;
sem_t sem1;
void* counting_thread(void* arg) {
sem_wait(&sem);
int offset = *(int*) arg;
int i;
for(i = 0; i < NUM_LOOPS; i++){
//sem_wait(&sem);
counter += offset;
printf("offset = %d\n", offset1);
//sem_post(&sem);
}
sem_post(&sem);
pthread_exit(NULL);
}
int main() {
sem_init(&sem, 0, 1);
pthread_t th1;
int offset = 1;
pthread_create(&th1, NULL, &counting_thread, &offset);
//sem_post(&sem1);
pthread_t th2;
offset = -1;
pthread_create(&th2, NULL, &counting_thread, &offset);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
printf("Finnal counter value: %lld\n", counter);
sem_destroy(&sem);
return 0;
}
解决方案
注释 有关 pthread_create() 在 *thread 中返回的线程 ID 的更多信息,请参见 pthread_self(3)。除非采用实时调度策略,否则在调用 pthread_create() 之后, 不确定哪个线程(调用者或新线程)接下来将执行。
不能保证谁将执行下一个。也许对您来说,main
线程正在执行下一个并offset to -1
在新线程之前进行设置,使其能够从中读取更新的值offset
is -1
。
您可以使用条件变量进行同步。
例如 :
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_LOOPS 1000
long long counter = 0;
sem_t sem;
sem_t sem1;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void* counting_thread(void* arg) {
sem_wait(&sem);
int offset = *(int*) arg;
pthread_cond_signal(&cond1);
int i;
for(i = 0; i < NUM_LOOPS; i++){
counter += offset;
printf("offset = %d\n", offset);
}
sem_post(&sem);
pthread_exit(NULL);
}
int main() {
sem_init(&sem, 0, 1);
int offset = 1;
pthread_t th1;
pthread_create(&th1, NULL, &counting_thread, &offset);
pthread_cond_wait(&cond1, &lock);
pthread_t th2;
offset = -1;
pthread_create(&th2, NULL, &counting_thread, &offset);
pthread_join(th1, NULL);
pthread_join(th2, NULL);
printf("Finnal counter value: %lld\n", counter);
sem_destroy(&sem);
return 0;
}
推荐阅读
- php - 无法访问数组中的值 - PHP
- firebase - 在 retool 如何使用 retool 连接和上传 Firebase 中的数据
- java - Java:如何从任意 Enum 类中获取值
- audio - FFMPEG 是否有防止剪辑的“守卫”?
- r - 从表达式字符串保存 RData 和 RDS 文件对象
- arrays - 如何将函数应用于json数组的每个元素?
- django - Django ImportError:模块“social_core.backends.google”未定义“GoogleOpenId”属性/类
- go - 选择性地向特定客户端发送事件
- python - Python - 根据表示列和行位置(坐标)的键将字典中的值写入 .csv
- r - 小册子问题编织参考在部分末尾