मैंने पाइथन में पहले मल्टीथ्रेडिंग लाइब्रेरी का उपयोग किया है, लेकिन यह पहली बार है जब मैं सी में थ्रेडिंग की कोशिश कर रहा हूं। मैं श्रमिकों का पूल बनाना चाहता हूं। बदले में, इन श्रमिकों चाहिए करने के लिए धक्का या queue.Following कोड काफी वहाँ अभी तक नहीं है से पॉप, लेकिन मैं अब तक क्या किया है है:थ्रेड सुरक्षित कतारों को कार्यान्वित करने के लिए कैसे करें
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUMTHREADS 20 /* number of threads to create */
typedef struct node node;
typedef struct queue queue;
struct node {
char *name;
node *next;
};
struct queue {
node *head;
node *tail;
};
/* pop: remove and return first name from a queue */
char *pop(queue *q)
{
if (q->head == NULL)
return NULL;
char *name = q->head->name;
node *tmp = q->head;
q->head = q->head->next;
free(tmp);
return name;
}
/* push: add name to the end of the queue */
int push(queue *q, char *name)
{
node *new = malloc(sizeof(node));
if (new == NULL)
return -1;
new->name = name;
new->next = NULL;
if (q->tail != NULL)
q->tail->next = new;
q->tail = new;
if (q->head == NULL) /* first value */
q->head = new;
return 0;
}
/* printname: get a name from the queue, and print it. */
void *printname(void *sharedQ)
{
queue *q = (queue *) sharedQ;
char *name = pop(q);
if (name == NULL)
pthread_exit(NULL);
printf("%s\n",name);
pthread_exit(NULL);
}
int main()
{
size_t i;
int rc;
pthread_t threads[NUMTHREADS];
char *names[] = {
"yasar",
"arabaci",
"osman",
"ahmet",
"mehmet",
"zeliha"
};
queue *q = malloc(sizeof(queue));
q->head = NULL;
q->tail = NULL;
/* number of elements in the array */
size_t numelems = sizeof(names)/sizeof(char *);
for (i = 0; i < numelems; i++) /* push each name */
push(q, names[i]);
for (i = 0; i < NUMTHREADS; i++) { /* fire up threads */
rc = pthread_create(&threads[i], NULL, printname,
(void *)q);
if (rc) {
printf("Error, return code from pthread is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
मैं कोड से ऊपर की कोशिश की है, और यह हमेशा एक नाम ठीक वैसे ही मुद्रित एक बार। यह किसी भी नाम को छोड़ नहीं पाया, या दो बार मुद्रित नाम। दूसरी तरफ, मुझे यकीन नहीं है कि इस कतार कार्यान्वयन को कैसे सुरक्षित किया गया है। तो मेरा सवाल है, क्या यह एक थ्रेडसेफ कतार है? यदि नहीं, तो क्यों नहीं? और इसे धागा सुरक्षित कैसे बनाया जाए?
structs को typedefs की आवश्यकता नहीं है; उनके पास पहले से ही एक प्रकार है। –