ch4-job-queue2

Chapter_4     job-queue1 job-queue3







job-queue2.c     ALP, p. 78-79


#include <stdio.h> // for printf(), NULL
#include <malloc.h> // for malloc(), free()
#include <pthread.h> // for pthread_t, pthread_create(), pthread_join(),
// pthread_mutex_t, PTHREAD_MUTEX_INITIALIZER, pthread_mutex_lock(),
// pthread_mutex_unlock()
// pthread.h includes bits/pthreadtypes.h, full path
// /usr/include/x86_64-linux-gnu/bits/pthreadtypes.h,
// which defines pthread_t and pthread_mutex_t

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
/* A mutex protecting job_queue: */
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;

void enqueue_job (struct job * new_job); // add new job to the queue

/* 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, job2->number = 2;
job_queue = job1->next = job2->next = NULL;
enqueue_job(job2); // add last (second) job to the queue
enqueue_job(job1); // add first job to the queue

pthread_t thread;
pthread_create (&thread, NULL, &thread_function, NULL);
pthread_join (thread, NULL);

return 0;
}

void enqueue_job (struct job * new_job) // add new job to the queue
{
pthread_mutex_lock (&job_queue_mutex);
new_job->next = job_queue;
job_queue = new_job;
pthread_mutex_unlock (&job_queue_mutex);
}

void process_job (struct job *);

/* Process queued jobs until the queue is empty: */
void* thread_function (void* arg)
{
struct job * next_job;

while(1)
{
/* Lock the mutex on the job queue: */
pthread_mutex_lock (&job_queue_mutex);
/* Now it's safe to check if the queue is empty: */
if (job_queue == NULL)
{next_job = NULL;}
else
{
next_job = job_queue; // Get the next available job
job_queue = job_queue->next; // Remove this job from the list
}
/* Unlock the mutex on the job queue because we're done with the
queue for now: */
pthread_mutex_unlock (&job_queue_mutex);
/* Was the queue empty? If so, end the thread: */
if (next_job == NULL) // we need to unlock the mutex before breaking
{break;} // out of while(1)
// else
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-queue2.c -o job-queue2 -lpthread
./job-queue2
Processing job 1...
Processing job 2...
*/









Chapter_4     job-queue1 BACK_TO_TOP job-queue3



Comments

Popular posts from this blog

Contents