pthread_cond 와 pthread_mutex의 관계에 대해서

jee9894의 이미지

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
 
int last;
int tmp;
int num;
int count;
 
pthread_mutex_t printer_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t printer_cond = PTHREAD_COND_INITIALIZER;
 
void *printer(void *arg){
	while(1){
		pthread_mutex_lock(&printer_mutex);
		pthread_cond_wait(&printer_cond, &printer_mutex);
		printf("Count #%d : %d\n", count, num);
		pthread_mutex_unlock(&printer_mutex);
	}
}
 
void *random_generator(void *arg){
 
	for(int i = 0; i < last; i++){
		pthread_mutex_lock(&printer_mutex);
		num = (rand() % 100) + 1;
		printf("count : %d\n", count);
		if( num % tmp == 0 ){
			printf("num : %d, tmp : %d\n", num, tmp);
			pthread_mutex_unlock(&printer_mutex);
			pthread_cond_signal(&printer_cond);
			count++;
		} else {
		pthread_mutex_unlock(&printer_mutex);
		count++;
		}
	}
	exit(0);
}
 
int main(int argc, char **argv){
	tmp = atoi(argv[1]);
	last = atoi(argv[2]);
 
	pthread_t printer_thread, random_thread;
 
	srand(time(NULL));
 
	pthread_create(&printer_thread, NULL, printer, NULL);
	pthread_create(&random_thread, NULL, random_generator, NULL);
 
	pthread_join(random_thread, NULL);
	pthread_join(printer_thread, NULL);
 
	return 0;
}

제가 3시간 넘게 고민중인데 도저히 pthread_cond 와 pthread_mutex의 상관관계에 대해 이해를 하지 못하겠습니다.

cond_wait이 있는 스레드가 먼저 실행되게 해서 cond_wait 함수에서 뮤텍스를 풀어주고 기다린다고 들었는데 기다리는 것 같지가 않습니다. 디버깅을 해봤는데 분명히 시그널을 날린 상황에서도 전혀 작동을 하지 않더라고요.....

스레드 두 개를 서로 왔다갔다 해야하는 상황에서는 어떤 식으로 사용해야 하는지 감이 안잡힙니다

질문은 다음과 같습니다

1. cond_wait을 무한루프로 묶어둬야 하는지 안묶어줘도 되는지(둘 다 해봤는데 wait함수가 기다리지를 않습니다 그냥 넘어갑니다 ㅠㅜ)

2. 또 뮤텍스들은 2개를 사용해야 하는지 1개를 사용해야 하는지(cond에 인자로 들어가는 뮤텍스들은 무엇을 하는건지 모르겠습니다 다른 뮤텍스를 넣어줘야 하나요? ㅜㅜ)

3. signal이 있는 스레드에서 signal을 내보내고 sleep(1)을 추가하였더니 제대로 작동하기는 합니다 하지만 고작 100개 시그널을 보내는데 100초라는 어마어마한 시간이 듭니다ㅜㅜ.
왜이런건지 이해가 안갑니다. 저는 분명히 뮤텍스로 묶어두고 있는데도 지멋대로 작동하고 움직이는것 같습니다 ㅜㅜ

스텍오버플로에서 찾아보고 링크걸린거도 다보고 unix프로그래밍 책을봐도 명쾌한 해답이 나와있지 않네요 너무 짧은 설명 또는 스레드 1개짜리 예제밖에 없던데 멀티 스레드 프로그래밍인데 어떻게 스레드 하나만 사용하나요... 스레드가 여러게 일때 어떻게 사용하는지 명쾌하게 알고싶습니다

pald의 이미지

이전에 좋은 댓글이 있어서 링크합니다.
https://kldp.org/node/143032

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.