ch4-job-queue1
Chapter_4 cxx-exit | job-queue2 |
job-queue1.c ALP, p. 76-77
#include <stdio.h> // for printf(), NULL
#include <malloc.h> // for malloc(), free()
#include <pthread.h> // for pthread_t, pthread_create(), pthread_join()
struct job
{
struct job * next; // Link field for linked list
int number;
/* Other fields describing work to be done... */
};
struct job * job_queue; // A linked list of pending jobs
/* Process queued jobs until the queue is empty: */
void * thread_function (void * arg);
int main()
{ // initialize the job queue:
struct job *job1, *job2;
job1 = (struct job *) malloc(sizeof(struct job));
job2 = (struct job *) malloc(sizeof(struct job));
job1->number = 1, job1->next = job2;
job2->number = 2, job2->next = NULL; // last job in the queue
job_queue = job1; // first job to be done
pthread_t thread;
pthread_create (&thread, NULL, &thread_function, NULL);
pthread_join (thread, NULL);
return 0;
}
void process_job (struct job *);
/* Process queued jobs until the queue is empty: */
void* thread_function (void* arg)
{
struct job * next_job;
while (job_queue != NULL)
{
next_job = job_queue; // Get the next available job
job_queue = job_queue->next; // Remove this job from the list
process_job (next_job); // Carry out the work
free(next_job); // Clean up
}
return NULL;
}
void process_job (struct job * current)
{
printf("Processing job %d...\n", current->number);
}
/*
gcc job-queue1.c -o job-queue1 -lpthread
./job-queue1
Processing job 1...
Processing job 2...
*/
Chapter_4 cxx-exit | BACK_TO_TOP | job-queue2 |
Comments
Post a Comment