














Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!















●
●
●
●
● (^) The first step is to actually create each pthread using the library routine pthread_create: int pthread_create(pthread_t *restrict thread, const pthread_attr_t restrict attr, void (start_routine)(void), void *restrict arg); ● (^) The arguments are as follows:
● (^) You'll recall from lab 3 that we used waitpid to tell the parent process to wait for its children. ● (^) We achieve similar behavior for threads with join: int pthread_join(pthread_t thread, void **value_ptr); ● (^) pthread_join will suspend execution of the calling process (or thread) until the target thread (the thread argument) has terminated. ● (^) value_ptr is a pointer to the data returned by the pthread_exit() library call. We do not use this data, so you can just pass in NULL here. ● (^) Again, use pthread_join in a for loop: for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); }
● (^) Now is a good time to go ahead and test the threaded program. To run the program, use: -bash-3.2$ ./ptcount OUTER_LOOP_MAX INNER_LOOP_MAX ● (^) Where OUTER_LOOP_MAX is the number of times the outer loop in each thread should iterate, and INNER_LOOP_MAX is the number of times the inner loop in each thread should iterate. ● (^) If you created and joined the PThreads correctly, you should see something like: -bash-3.2$ ./ptcount 10 50 Thread: 0 finished. Counted: 500 Thread: 1 finished. Counted: 500 Thread: 2 finished. Counted: 500 Main(): Waited on 3 threads. Final value of count = 1500. Done. ● (^) Which is exactly what we wanted. Each thread increments the count 500 times (10*50=500) and the final value of count is 1500 because we have three threads.
● (^) Each thread updates the count using the ++ operator in C: count++; ● (^) Observe that this one line instruction in C, is actually implemented by three instructions in the x86 hardware: mov $(C_ADDR), %eax ; Move count into a register add 1, %eax ; Add 1 to count mov %eax, $(C_ADDR) ; Store count back into memory ● (^) Now, recall that each thread is sharing only one copy of count, which is loaded from memory and stored again each time the thread increments it. ● (^) While this does not explain our behavior yet, it's necessary for understanding the solution.
● (^) Recall from lecture that the Linux scheduler is preemptive. That is, the scheduler has the ability to stop a running process (with the intention of resuming it later) and replace it with another running process. ● (^) Now, imagine a scenario where the scheduler just happened to interleave our running threads in the following way: T1 T
●