关于信号量代码中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
相关产品推荐
相关产品推荐

