【发布时间】:2019-03-09 04:38:45
【问题描述】:
我编写了一个程序,其中主线程创建了 2 个子线程。等待一个随机时间,然后产生一个介于 1 和 6 之间的随机值,并将该值放入 randomValue 变量中。另一个等待并读取全局变量randomValue并打印该变量。所以我使用单个信号量来确保读取的线程将始终读取另一个线程写入的值。
我想修改每个线程我不知道 x 循环(2,3...),以便它可以产生 x 次随机值并将这个值放入 randomValue 并且另一个线程将读取x 乘以 randomValue 变量并将其打印出来。欢迎任何修改代码的想法。非常感谢。
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <semaphore.h>
/* variable shared by producer and consumer
(producer writes a value between 1 and 6) */
long randomValue = 0;
/**semaphore **/
sem_t mex;
// function that create a random sleep-time (to induce unpredictability)
static int duration(int min, int max)
{
static int first_time = 1;
// Seed the random number generator with the current time
// of day if we haven't done so yet.
if (first_time) {
first_time = 0;
srand48((int) time(NULL));
}
return (int) (min + drand48()*(max - min));
}
/* producer program */
void *producer(void *arg) {
char statearray[256];
// Initialize random generator
// Note that initstate and random are not threadsafe
initstate(time(NULL), statearray, 256);
sleep(duration(1,3));
printf("prod: producing ...\n");
//random value 1 et 6
randomValue = random();
randomValue = ((double) randomValue / RAND_MAX)*6+1;
//put the value
printf("prod: delivering %ld\n", randomValue);
sem_post(&mex);
pthread_exit(NULL);
}
/* consumer program */
void *consumer(void *arg) {
sleep(duration(1,5));
sem_wait(&mex);
printf("cons: consuming ...\n");
//
printf("cons: received %ld\n", randomValue);
pthread_exit(NULL);
}
/* main thread */
int main(int argc, char *argv[]) {
pthread_t tidprod, tidcons;
if (sem_init(&mex,0,0) != 0){
perror("sem_init");
exit(EXIT_FAILURE);
}
if (pthread_create(&tidprod, NULL, producer, NULL) != 0) {
perror("pthread_create");
}
if (pthread_create(&tidcons, NULL, consumer, NULL) != 0) {
perror("pthread_create");
}
if (pthread_join(tidcons, NULL) != 0) {
perror("pthread_join prod");
}
if (pthread_join(tidprod, NULL) != 0) {
perror("pthread_join prod");
}
fflush(stdout);
pthread_exit(EXIT_SUCCESS);
}
【问题讨论】:
标签: c pthreads mutex semaphore