threads.c 836 Bytes
#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;

}