【发布时间】:2018-11-02 02:11:08
【问题描述】:
我有两个问题:
- 此代码中的变量 sum 和 counter 定义为 长长 ?我将它们更改为 int ,但它没有给我类似的计数,就像没有线程和信号量的代码一样!为什么 count 会得到半随机值(即使在 for 循环中再次将其设置为零)?
- 我怎样才能达到 1+2+3.../10 ?我的意思是,类型的影响是什么
变量(与信号量、进程和线程无关的变量。即
pid_t)?
提前谢谢你。
#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;
}
【问题讨论】:
-
您得到半随机值,因为程序在执行上花费了不同的时间(
running之间的时间设置为 1,然后设置为 0)。
标签: c multithreading pthreads semaphore