쓰레드를 주고 받을때 같은 값을 가져가서 덮어 쓴느 경우가 생긴다

 

그러면 계산된 값이 둘중에 한 애꺼만 받게 되는데 

그래서 한녀석 계산 끝날때까지 기다렷다가

하면 된다

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define NUM_THREAD 100

void * thread_inc(void * arg);
void * thread_des(void * arg);

long long num=0;
pthread_mutex_t mutex;

int main(int argc, char *argv[])
{
	pthread_t thread_id[NUM_THREAD];
	int i;

	pthread_mutex_init(&mutex, NULL);

	for(i=0; i<NUM_THREAD; i++)
	{
		if(i%2)
			pthread_create(&(thread_id[i]), NULL, thread_inc, NULL);
		else
			pthread_create(&(thread_id[i]), NULL, thread_des, NULL);
	}

	for(i=0; i<NUM_THREAD; i++)
		pthread_join(thread_id[i], NULL);

	printf("result: %lld \n", num);
	pthread_mutex_destroy(&mutex);
	return 0;
}

void * thread_inc(void * arg)
{
	int i;
	pthread_mutex_lock(&mutex);
	for(i=0; i<50000000; i++)
		num+=1;
	pthread_mutex_unlock(&mutex);
	return NULL;
}

void * thread_des(void * arg)
{
	int i;
	pthread_mutex_lock(&mutex);
	for(i=0; i<50000000; i++)
		num-=1;
	pthread_mutex_unlock(&mutex);
	return NULL;
}

이똥색의 뜻을 알았다

쓰레드 중복되고 계속 돌아갈거같은거 똥색임

상관없음 리눅스에선 

 

언제나 에러와 함께하는 나~

 

변함없는 모습 음음 좋아

 

gcc mutex.c -D_REENTRANT -o mutex -lpthread 

이게 중요함 선언할때 스레드 그 장굼도 넣어준다는 뜻

'[ 충남인력개발원 ] (2019) > ┗TCP&IP' 카테고리의 다른 글

리눅스 체팅 연동  (0) 2019.11.28
쓰레드 키주고 받으면서 하기  (0) 2019.11.27
쓰레드 주고 받기 우아아  (0) 2019.11.27
프로세스 쓰레드  (0) 2019.11.27
git hub 추가 하기  (0) 2019.11.27
블로그 이미지

Or71nH

,