【发布时间】:2020-11-17 06:37:49
【问题描述】:
我正在学习队列以及如何使用线程池来实现它们(这两个对我来说都是相当新的)。我以为我修改了我在网上找到的正确示例,但是我的线程函数中的 pclient 变量始终为 NULL。有没有经验丰富的人知道是怎么回事?
main.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <pthread.h>
#include "myqueue2.h"
#define THREAD_POOL_SIZE 3
#define MAX_INT 10
pthread_t thread_pool[THREAD_POOL_SIZE];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *thread_function(void *arg);
int main(int argc, char **argv)
{
queue q1;
// Create a bunch of threads to handle future data
for(int i=0; i < THREAD_POOL_SIZE; i++){
pthread_create(&thread_pool[i], NULL, thread_function, NULL);
printf("Thread %d created\n",i);
}
printf("Threads created\n");
//Create linked list
for(int i=0; i < MAX_INT; i++){
pthread_mutex_lock(&mutex);
int *client = malloc(sizeof(int));
*client = i;
enqueue(&i);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *thread_function(void *arg){
while (true){
int *pclient = dequeue();
if (pclient != NULL){
//We have stuff to do
int t;
pthread_mutex_lock(&mutex);
t = dequeue();
pthread_mutex_unlock(&mutex);
printf("t = %d\n",t);
} else {
printf("No work to do\n");
}
}
}
myqueue2.c
#include "myqueue2.h"
#include <stdlib.h>
node_t *head = NULL;
node_t *tail = NULL;
void enqueue(int *value){
node_t *newnode = malloc(sizeof(node_t));
newnode->value = value;
newnode->next = NULL;
//if there is a tail, connect that tail to this new node.
if (tail == NULL){
head = newnode; //make sure the head still makes sense
} else {
tail->next = newnode;
}
tail = newnode;
}
int* dequeue(){
//make sure queue is empty
if (head == NULL){
return NULL;
} else{
//save result we want to return
int *result = head->value;
//save head of queue
node_t *tmp = head;
// take it off the queue
head = head->next;
if (head == NULL){tail = NULL;}
free(tmp);
return result;
}
}
myqueue2.h
#ifndef MYQUEUE_H_
#define MYQUEUE_H_
typedef struct node {
int value;
struct node *next;
} node;
typedef struct node node_t;
typedef struct{
node *head;
node *tail;
} queue;
void enqueue(int *value);
int* dequeue();
#endif
【问题讨论】:
-
警告太多了!你没有启用警告吗? (我使用
-Wall -Wextra -pedantic和gcc) -
你不能在没有锁的情况下调用
dequeue。您可以在thread_function中的if中执行此操作。
标签: c queue threadpool