Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the code shown below for a simple linked stack implementation struct li

ID: 3710427 • Letter: C

Question

Consider the code shown below for a simple linked stack implementation struct list void 'val: struct 1ist "next h : struct list copNULL /" Push a new item on the stack int stack push (void iten) struct list new new-malloc(s?zeofistruet list)); new->val-item new->next-top: cop new return 0 int stack pop (void item) struet 1iat ur top: it eurrt zeturn -1:Stack is empty toptop->nex retuzn 0 If mutiple threads execute stack push at the same time, how could a race result, and how would this manifest in the program? push at the same tme, how, coul - T TT Arial

Explanation / Answer

Since every thread has its own stack and local variables, so if multiple threads access local variables, there will be an error. But global variables or static variables occupy data segment and is shared by all threads, there will not occur if multiple threads access global variables simultaneously.

In your code, if multiple threads execute stack_push function, there will be a chance of error as stack_top is common to all threads and threads may overwrite on other's item as in case of SPOOLER directory problem in synchronisation.

Meanwhile if you want to implement multi threading in C language, POSIX Threads or Pthreads is standard for threads and its implementation is available with gcc compiler.

You have to include pthread library. In main() we deaclare a variable called thread_id, which is of type pthread_t, which is an integer used to identify the thread in the system. After declaring thread_id, we call pthread_create() function to create a thread.

int main(){

pthread_t tid;

pthread_create(&tid, NULL, myThreadFun, param);

pthread_join(tid,NULL);

}

pthread_create() takes 4 arguments

First argument is a pointer to thread_id which is set by this function.

Third argument is name of the function to be executed for thread to be created.

Fourth argument is used to pass arguments to thread.

The pthread_join() function for threads is equivalent of wait() for processes. A call to pthread_join blocks the calling thread until the thread with identifier equal to first argument terminates.

To compile a multithread program using gcc, we need to link it with pthread library.