Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Note To compile thread-based programs you must use the -pthread compiler option.
- This ensures linking with the libpthread library and with the thread-safe
- functions of the C library.
- IMP. Follow an incremental code development approach. If you write all the code
- in a single go and only then compile it, you risk spending the following 15
- minutes eliminating the compilation errors and the remaining class debugging it.
- Instead, you should add code step by step, compiling it and testing it, after
- each step.
- In this problem you will write a very simple multi-threaded program that
- increments a shared counter.
- The program's main thread creates 3 other threads.
- Each ot these 3 threads shall increment a shared counter (long int) a number of
- times, specified as a command line argument to the program.
- The main thread shall wait for the termination of the other 3 threads, and then
- shall print the final value of the counter.
- Compile your program and run it several times. Explain the observed results.
- */
- #include <stdio.h>
- #include <pthread.h>
- #include <stdlib.h>
- typedef struct __myarg_t{
- long int counter;
- long int num_increments;
- } myarg_t;
- void *increment(void *args){
- myarg_t *res = (myarg_t *) args;
- for(int i = 0; i < res->num_increments; i++){
- ++res->counter;
- }
- return (void *) res->counter;
- }
- int main(int argc, char* argv[]){
- if(argc == 2){
- myarg_t args;
- args.counter = 0;
- args.num_increments = atoi(argv[1]);
- long int t1_counter, t2_counter, t3_counter;
- pthread_t t1, t2, t3;
- //while(args.counter < args.num_increments){
- t1_counter = pthread_create(&t1, NULL, increment, &args);
- t2_counter = pthread_create(&t2, NULL, increment, &args);
- t3_counter = pthread_create(&t3, NULL, increment, &args);
- pthread_join(t1, (void **) &t1_counter);
- pthread_join(t2, (void **) &t2_counter);
- pthread_join(t3, (void **) &t3_counter);
- printf("Thread 1 has counter = %ld\n", t1_counter);
- // printf("Thread 2 has counter = %ld\n", t2_counter);
- // printf("Thread 3 has counter = %ld\n", t3_counter);
- //}
- printf("%ld\n", args.counter);
- }
- else if (argc < 2) printf("Few Arguments!\n");
- else printf("Too Many Arguments!\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement