[완료] EC++ 책 응용하면 pthread_mutex 제대로 안되는 듯한 문제

j2g1의 이미지

스콧 마이어스 EC++ 공부하면서 pthread_mutex_lock/unlock 사용하는 프로그램 짜보고 있는데, 책 대로라면 원래 필요없을 unLock()함수를 사용해야만 제대로 동작하는 듯 합니다.
뭐가 문제인지 모르겠네요. 조언 부탁 드립니다...

// g++ test.cpp -o test -lpthread

// kdlp 게시판에 <<>>가 안먹어서 아래에는 생략
#include iostream
#include stdlib.h
#include pthread.h
#include exception

using namespace std;

#define NUM_THREADS 2
#define RUN_TIME 20

bool thread1_run = true;
bool thread2_run = true;
pthread_mutex_t *mutex;
int shared_data = 0;

class Lock {
public:
explicit Lock(pthread_mutex_t *pm)
:mutexPtr(pm)
{
rc = pthread_mutex_lock(mutexPtr);
}

~Lock()
{
pthread_mutex_unlock(mutexPtr);
}

/* void unLock(pthread_mutex_t *pm)
{
pthread_mutex_unlock(pm);
}
*/

private:
pthread_mutex_t *mutexPtr;
int rc;
};

void *PrintHello(void *threadid);
void *PrintHi(void *threadid);

int main()
{
pthread_mutex_init(mutex, 0);

pthread_t threads[NUM_THREADS];
int arg = 0;

pthread_create(&threads[0], NULL, PrintHello, (void *)(arg++));
pthread_create(&threads[1], NULL, PrintHi, (void *)(arg++));


pthread_exit(NULL);

pthread_mutex_destroy(mutex);

return 0;

}

void Hello(long tid, int i)
{
Lock lock1(mutex);
try{
shared_data += 10;
cout << "tid=" << tid << ", data:" << shared_data << " ,cnt:" << i << endl;
shared_data -= 10;
// something important code might be here to use the shared data
}
catch (exception& e){
cout << "exception:" << e.what() << endl;
}

// lock1.unLock(mutex);
}

void Hi(long tid, int i)
{
Lock lock2(mutex);
try{
shared_data++;
cout << "tid=" << tid << ", data:" << shared_data << " ,cnt:" << i << endl;
shared_data--;
// something important code might be here to use the shared data
}
catch (exception& e){
cout << "exception:" << e.what() << endl;
}

// lock2.unLock(mutex);
}

void *PrintHello(void *threadid)
{
int i=1;
long tid = (long)threadid;

while (thread1_run) {

Hello(tid, i);

sleep(1);
i++;
if (i > RUN_TIME)
thread1_run = false;
}

pthread_exit(NULL);
}

void *PrintHi(void *threadid)
{
int i=1;
long tid = (long)threadid;

while (thread2_run) {

Hi(tid, i);

sleep(1);
i++;
if (i > RUN_TIME)
thread2_run = false;
}

pthread_exit(NULL);
}

bushi의 이미지

@@ -42,6 +42,7 @@
 
 int main()
 {
+	mutex = (pthread_mutex_t *)malloc(sizeof(*mutex));
 	pthread_mutex_init(mutex, 0);
 
 	pthread_t threads[NUM_THREADS];
@@ -51,9 +52,11 @@
 	pthread_create(&threads[1], NULL, PrintHi, (void *)(arg++));
 
 
-	pthread_exit(NULL);
+	pthread_join(threads[0], NULL);
+	pthread_join(threads[1], NULL);
 
 	pthread_mutex_destroy(mutex);
+	free(mutex);
 
 	return 0;
 

-lpthread 대신 -pthread 사용하세요.
링크 옵션 뿐만 아니라 필요한 컴파일 옵션까지 조정됩니다. 그게 뭐든 간에.

j2g1의 이미지

감사합니다 ^^. -pthread 옵션을 쓰면 unrecognized option이라고 나와서 -lpthread 그냥 사용했습니다.

bushi의 이미지