gpt4 book ai didi

创建 Pthreads

转载 作者:行者123 更新时间:2023-11-30 21:26:11 26 4
gpt4 key购买 nike

我正在尝试为函数 * Producer 创建一个线程,但用于创建线程的行显示错误。我为这句话加了星标,但我无法弄清楚它出了什么问题......

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>

#define TOTALLOOPS 100 /*Num of loops run*/
#define NUMOFPAIRS 4 /*For each 1 it produces 1 consumer and 1 producer*/

typedef struct {
int q[NUMOFPAIRS];
int head;
int tail;
int full;
int empty;
pthread_mutex_t mut; /*Creates a mutex Lock*/
pthread_cond_t notFull; /*Creates conditional*/
}Queue;

int main(void)
{
Queue buf; /* Declare and initialize parts of struct */
buf.head = 0;
buf.tail = 0;
buf.full = 0;
buf.empty = 0;
pthread_mutex_init(&buf.mut, NULL);/*intitializes mutex for struct*/
//pthread_cond_init(&buf.nutFull, NULL);

pthread_t pro;
**pthread_create(&pro, NULL, producer, &buf);**


pthread_mutex_destroy(&buf.mut);
return 0;
}

void *producer(int x, Queue *buf){
int id = x;
int i;

for(i = 0; i < TOTALLOOPS; i++){

while(buf->full == 1){
//do nothing
}
mClock();
printf(" - Producer%d:\n", id);
}
}

void* consumer(int x, Queue *buf){
int id = x;
int i;

for(i = 0; i < TOTALLOOPS; i++){

while(buf->empty == 1){
//do nothing
}
mClock();
printf(" - Consumer%d:\n", id);
}
}

void addToQueue(Queue *buf, int x){
//Checks if empty flag is triggered, if so un triggers
if(buf->empty) buf->empty = 0;

buf->q[buf->tail] = x;
if(buf->tail == 3) buf->tail = 0; /*Resets to beginning if at end*/
else buf->tail += 1; /*else just moves to next*/

//Checks if full flag needs to be triggered, if so triggers
if(buf->tail == buf->head) buf->full = 1;
}

int removeFromQueue(Queue *buf){
int t; /*return value from queue*/

//Checks if full flag is triggered, if so un triggers
if(buf->full == 1)buf->full = 0;

t = buf->q[buf->head];
if(buf->head == 3) buf->head = 0; /*Resets to beginning if at end*/
else buf->head += 1; /*else just moves to next*/

//Checks if full flag needs to be triggered, if so triggers
if(buf->tail == buf->head) buf->empty = 1;

return t;
}

void mClock(){
struct timeval tv;
gettimeofday(&tv,NULL);
long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;
printf("%u", time_in_micros);
}

最佳答案

您必须在 pthread_create 调用之前声明生产者。

void *producer(int x, Queue *buf);

应该首先出现。

同样,mClock 必须首先声明。

此外,该函数应该只接受一个参数

关于创建 Pthreads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19554189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com