【问题标题】:defining variables for semaphore为信号量定义变量
【发布时间】:2018-11-02 02:11:08
【问题描述】:

我有两个问题:

  1. 此代码中的变量 sum 和 counter 定义为 长长 ?我将它们更改为 int ,但它没有给我类似的计数,就像没有线程和信号量的代码一样!为什么 count 会得到半随机值(即使在 for 循环中再次将其设置为零)?
  2. 我怎样才能达到 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


【解决方案1】:

1.该代码中的变量 sum 和 counter 定义为 long long ?我将它们更改为 int ,但它没有给我类似的计数,

不确定你的意思。将countersumint 更改为long long(并相应地调整% 格式说明符,例如%d)不应该(有意义地)改变程序的含义。在 x86_64 Linux 中,您将使用 32 位计数器,而不是 64 位计数器。

喜欢没有线程和信号量的代码!

好吧,我们需要查看其他程序,但请看下面。

为什么 count 会得到半随机值(即使在 for 循环中再次将其设置为零)?

因为有两个并发线程在运行。一个是递增计数器,另一个是每秒重置一次。无法预测其他线程将能够增加计数器多少次。这将取决于系统的负载(在同一台机器上的运行之间)和系统本身(在机器之间,即它有多快)。

通常,唯一可以“预测”计数器值的系统是具有非 OOO、具有确定性调度程序/操作系统等的固定频率处理器的系统。普通桌面不是这样的机器 - - 事实上,完全相反!

我建议阅读操作系统、它们的调度程序、时间片等。

【讨论】:

  • 首先非常感谢。如果我想解释更多:我的意思是将 long Long 计数的定义更改为 int count 和 sum 相同。在进行此更改并将 %lld 更改为 %d 之后,结果没有任何变化(您已解释过)。我在我的问题中犯了一个错误: int counter ,给了我类似的半随机结果,对此感到抱歉。我认为改变计数器的类型,可以改变结果。 @橡子
猜你喜欢
  • 1970-01-01
  • 2014-12-06
  • 2013-03-07
  • 2011-03-31
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
相关资源
最近更新 更多