You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于信号量代码中long long变量替换及求和问题的技术问询

附你的原始代码(方便参考):

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <semaphore.h>
sem_t s1;
char running = 1;
long long counter = 0;
void * process() {
    while (running) {
        sem_wait(&s1);
        counter++;
        sem_post(&s1);
    }
    printf("Thread: exit\n");
    pthread_exit(NULL);
}
int main() {
    int i;
    long long sum = 0;
    pthread_t thread_Id;
    sem_init(&s1, 0, 1);
    if (pthread_create(&thread_Id, NULL, process, NULL)) {
        printf("ERROR in pthread_create()\n");
        exit(-1);
    }
    for (i=0 ; i < 10 ; i++) {
        sleep(1);
        sem_wait(&s1);
        printf("counter = %lld\n", counter);
        sum += counter;
        counter = 0;
        sem_post(&s1);
    }
    sem_wait(&s1);
    running = 0;
    sem_post(&s1);
    pthread_join(thread_Id, NULL);
    printf("Average Instructions = %lld \n", sum/10);
    return 0;
}

内容的提问来源于stack exchange,提问作者Arash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:44:05