source: liacs/os/assignment4/assignment4a.c@ 250

Last change on this file since 250 was 2, checked in by Rick van der Zwet, 15 years ago

Initial import of data of old repository ('data') worth keeping (e.g. tracking
means of URL access statistics)

File size: 1.7 KB
RevLine 
[2]1/*
2 * Rick van der Zwet
3 * 0433373
4 * OS Assigment 3 - Part A
5 * Licence: BSD
6 * $Id: assignment4a.c 539 2008-04-01 20:23:55Z rick $
7 */
8
9#include <sysexits.h>
10#include <stdlib.h>
11#include <pthread.h>
12#include <stdio.h>
13#include <unistd.h>
14
15#define MAXCOUNTER 999999
16
17struct thread_data {
18 int *account1;
19 int *account2;
20 int threadid;
21};
22
23static int go_quit = 0;
24
25void *balance(void *threadarg) {
26 struct thread_data *my_data;
27 my_data = (struct thread_data *) threadarg;
28
29 int counter, temp1, temp2, amount;
30 int *account1, *account2;
31 account1 = my_data->account1;
32 account2 = my_data->account2;
33
34 counter = 0;
35 do {
36 temp1 = *account1;
37 temp2 = *account2;
38 amount = random() % 100;
39// printf("%i - %i: Temp1 %i, temp2 %i, amount %i\n", my_data->threadid,
40// counter, temp1, temp2, amount);
41 *account1 = temp1 - amount;
42 *account2 = temp2 + amount;
43 counter++;
44 } while (*account1+*account2 == 0 && counter < MAXCOUNTER && go_quit == 0);
45 if (go_quit == 0) {
46 printf("counter: %i\n", counter);
47 go_quit = 1;
48 }
49 pthread_exit(NULL);
50}
51
52
53
54int main (int argc, char * argv[]) {
55
56 pthread_t thread0, thread1;
57 int account1, account2;
58 struct thread_data thread0_data, thread1_data;
59 thread0_data.account1 = &account1;
60 thread0_data.account2 = &account2;
61 thread0_data.threadid = 0;
62 thread1_data.account1 = &account1;
63 thread1_data.account2 = &account2;
64 thread1_data.threadid = 1;
65
66 account1 = 0;
67 account2 = 0;
68 pthread_create(&thread0, NULL, balance, (void *) &thread0_data);
69 pthread_create(&thread1, NULL, balance, (void *) &thread1_data);
70
71 pthread_exit(NULL);
72 return(EX_OK);
73}
Note: See TracBrowser for help on using the repository browser.