Jim

threads

No preview for this file type
1 #include <stdio.h> 1 #include <stdio.h>
2 #include <pthread.h> 2 #include <pthread.h>
3 3
4 -void* worker1(void* tname){ 4 +int data =0;
5 - 5 +
6 - 6 +struct worker_data {
7 - while(1){ 7 + pthread_mutex_t mutex;
  8 +};
  9 +
  10 +void* worker1(void* _arg){
  11 +
  12 + struct worker_data* arg=(struct worker_data*)_arg;
  13 + int i;
  14 +/* while(1){
8 15
9 write (1, "11111111\n", 9); 16 write (1, "11111111\n", 9);
10 sleep(3); 17 sleep(3);
11 - } 18 + } */
  19 +
  20 + for (i=0; i < 10000000; i++){
  21 + pthread_mutex_lock(&(arg->mutex));
  22 + data +=1;
  23 + pthread_mutex_unlock(&(arg->mutex));
  24 + }
  25 +
12 } 26 }
13 27
14 -void* worker2(void* tname){ 28 +void* worker2(void* arg){
15 29
16 30
17 while(1){ 31 while(1){
@@ -22,12 +36,16 @@ void* worker2(void* tname){ @@ -22,12 +36,16 @@ void* worker2(void* tname){
22 36
23 int main(){ 37 int main(){
24 38
25 - pthread_t tid1, tid2; 39 + struct worker_data arg;
26 40
27 - pthread_create(&tid1, NULL, worker1, NULL); 41 + pthread_mutex_init(&(arg.mutex), NULL);
28 - pthread_create(&tid2, NULL, worker2, NULL); 42 +
  43 + pthread_t tid1, tid2;
  44 + pthread_create(&tid1, NULL, worker1, (void*)&arg);
  45 + pthread_create(&tid2, NULL, worker1, (void*)&arg);
29 pthread_join (tid1, NULL); 46 pthread_join (tid1, NULL);
30 pthread_join (tid2, NULL); 47 pthread_join (tid2, NULL);
  48 + printf("%d\n", data);
31 return 0; 49 return 0;
32 50
33 } 51 }
No preview for this file type
  1 +#include <stdio.h>
  2 +#include <pthread.h>
  3 +
  4 +
  5 +struct worker_data {
  6 + pthread_mutex_t mutex;
  7 + int data;
  8 +};
  9 +
  10 +void* worker1(void* _arg){
  11 +
  12 + struct worker_data* arg=(struct worker_data*)_arg;
  13 + int i;
  14 +/* while(1){
  15 +
  16 + write (1, "11111111\n", 9);
  17 + sleep(3);
  18 + } */
  19 +
  20 + for (i=0; i < 10000000; i++){
  21 + pthread_mutex_lock(&(arg->mutex));
  22 + arg->data +=1;
  23 + pthread_mutex_unlock(&(arg->mutex));
  24 + }
  25 +
  26 +}
  27 +
  28 +void* worker2(void* arg){
  29 +
  30 +
  31 + while(1){
  32 + write(2, "22222222\n", 9);
  33 + sleep(3);
  34 + }
  35 +}
  36 +
  37 +int main(){
  38 +
  39 + struct worker_data arg;
  40 +
  41 + arg.data = 0;
  42 +
  43 + pthread_mutex_init(&(arg.mutex), NULL);
  44 +
  45 + void* args = (void*)&arg;
  46 + args->data = 3;
  47 +
  48 + pthread_t tid1, tid2;
  49 + pthread_create(&tid1, NULL, worker1, args);
  50 + pthread_create(&tid2, NULL, worker1, args);
  51 + pthread_join (tid1, NULL);
  52 + pthread_join (tid2, NULL);
  53 + printf("%d\n", arg.data);
  54 + return 0;
  55 +
  56 +}
  57 +
  58 +