뮤텍스로 스레드를 완료하고 싶습니다. 첫 번째 스레드는 실행되지 않고 스레드 2 & 3이 실행됩니다.뮤텍스가있는 첫 번째 스레드를 실행할 수 없습니다.
누구든지이 문제의 원인을 알고 있습니까? 스레드 1이 실행되었지만 2 또는 3이 실행되지 않는 경우가 있습니다. 나는 여기에 어떤 문제가 있는지 모른다.
Thread created successfully
Thread created successfully
Thread created successfully
----------------------------------------------------
J:0
NUM_REQUESTS (before function): 0
J:0
----------------------------------------------------
----------------------------------------------------
J:1
Third thread processing done
WRITE DATA TO LIST!
NUM_REQUESTS(function): 1
NUM_REQUESTS (before function): 0
J:1
----------------------------------------------------
----------------------------------------------------
J:2
Second thread processing done
WRITE DATA TO LIST!
NUM_REQUESTS(function): 0
NUM_REQUESTS (before function): 0
J:2
----------------------------------------------------
프로그램 :
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t request_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t got_request = PTHREAD_COND_INITIALIZER;
pthread_t tid[3];
int thr_id[3];
int ret1,ret2,ret3;
int i = 0;
int err;
int *ptr[2];
int num_requests = 0;
int rc = 0;
이 스레드의 기능이는 첫 번째 스레드가 실행되지 않습니다!
void* doSomeThing(void *arg)
{
unsigned long i = 0;
pthread_t id = pthread_self();
for(i=0; i<1000000;i++);
if(pthread_equal(id,tid[0]))
{
printf("First thread processing done\n");
printf("WRITE DATA TO LIST!\n");
num_requests--;
printf("NUM_REQUESTS(function): %d\n",num_requests);
rc = pthread_mutex_unlock(&request_mutex);
pthread_exit(&tid[0]);
}else if(pthread_equal(id,tid[1])){
printf("Second thread processing done\n");
num_requests--;
printf("WRITE DATA TO LIST!\n");
printf("NUM_REQUESTS(function): %d\n",num_requests);
rc = pthread_mutex_unlock(&request_mutex);
pthread_exit(&tid[1]);
}else if(pthread_equal(id,tid[2])){
printf("Third thread processing done\n");
printf("WRITE DATA TO LIST!\n");
printf("NUM_REQUESTS(function): %d\n",num_requests);
num_requests--;
rc = pthread_mutex_unlock(&request_mutex);
pthread_exit(&tid[2]);
}
return NULL;
}
난에만 스레드를 생성하고 스레드 어떤
int main(void)
{
//create 3 threads
while(i < 3)
{
thr_id[i] = i;
err = pthread_create(&(tid[i]), NULL, &doSomeThing, (void*)&thr_id[i]);
if (err != 0)
printf("can't create thread :[%s]", strerror(err));
else
printf("Thread created successfully\n");
i++;
}
int j;
for(j=0;j<3;j++){
add_request(j, &request_mutex, &got_request);
}
return 0;
}
에서 https://computing.llnl.gov/tutorials/pthreads/samples/condvar.c 도 21의를 수행 할 것입니다. 그 후 나는 잠금을 해제합니다. 그런 다음 스레드를 처리하기 위해 다시 뮤텍스를 잠급니다. 그 함수에서 뮤텍스를 다시 해제합니다. 무슨 뜻인지 이해가 안 되니? 나는 또한 multithreading에서 새롭다. 나는 mutex를 항상 잠그고 잠급니다. 아니? 팁 주셔서 감사합니다. 앞으로 pthread를 사용할 것입니다. 감사합니다. –
모든 요청을 완료하고 싶습니다. 그래서 이것은 그것을 배우기 시작하는 간단한 예입니다. 그래서 내가하고 싶은 일은 3 개의 스레드를 끝내는 것입니다. –
doSomeThing을 호출 할 수 있다는 것을 이해해야합니다. * BEFORE * 요청을 추가하십시오. –