Jim

threads

No preview for this file type
#include <stdio.h>
#include <pthread.h>
void* worker1(void* tname){
while(1){
int data =0;
struct worker_data {
pthread_mutex_t mutex;
};
void* worker1(void* _arg){
struct worker_data* arg=(struct worker_data*)_arg;
int i;
/* while(1){
write (1, "11111111\n", 9);
sleep(3);
}
} */
for (i=0; i < 10000000; i++){
pthread_mutex_lock(&(arg->mutex));
data +=1;
pthread_mutex_unlock(&(arg->mutex));
}
}
void* worker2(void* tname){
void* worker2(void* arg){
while(1){
... ... @@ -22,12 +36,16 @@ void* worker2(void* tname){
int main(){
pthread_t tid1, tid2;
struct worker_data arg;
pthread_create(&tid1, NULL, worker1, NULL);
pthread_create(&tid2, NULL, worker2, NULL);
pthread_mutex_init(&(arg.mutex), NULL);
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, worker1, (void*)&arg);
pthread_create(&tid2, NULL, worker1, (void*)&arg);
pthread_join (tid1, NULL);
pthread_join (tid2, NULL);
printf("%d\n", data);
return 0;
}
... ...
No preview for this file type
#include <stdio.h>
#include <pthread.h>
struct worker_data {
pthread_mutex_t mutex;
int data;
};
void* worker1(void* _arg){
struct worker_data* arg=(struct worker_data*)_arg;
int i;
/* while(1){
write (1, "11111111\n", 9);
sleep(3);
} */
for (i=0; i < 10000000; i++){
pthread_mutex_lock(&(arg->mutex));
arg->data +=1;
pthread_mutex_unlock(&(arg->mutex));
}
}
void* worker2(void* arg){
while(1){
write(2, "22222222\n", 9);
sleep(3);
}
}
int main(){
struct worker_data arg;
arg.data = 0;
pthread_mutex_init(&(arg.mutex), NULL);
void* args = (void*)&arg;
args->data = 3;
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, worker1, args);
pthread_create(&tid2, NULL, worker1, args);
pthread_join (tid1, NULL);
pthread_join (tid2, NULL);
printf("%d\n", arg.data);
return 0;
}
... ...