그래서 전역 정수를 증가시키는 3 개의 쓰레드가 필요합니다. 나는 스레드가 만들어 졌을 때 그 메인에있는 포크에 simulair라는 것이 새로 생성 된 스레드와 동시에 코드를 계속 실행한다고 생각했다. 두 번째와 세 번째 스레드는 첫 번째 스레드가 완료 될 때까지 생성되지 않으므로 그다지 일어나지 않습니다.쓰레드가 simultaniously로 실행 중임
void * say_it(void *)
{
int count = 0;
while(BUFFER < 24)
{
//LOCK
if (pthread_mutex_lock(&output_lock) != 0)
{
perror("Could not lock output: ");
exit(-1);
}
//print message
cout << "TID: " << pthread_self() << " PID: " << "WORK IN PROGRESS " << "Buffer: " << BUFFER << endl;
BUFFER++;
//UNLOCK
if (pthread_mutex_unlock(&output_lock) != 0)
{
perror("Could not unlock output: ");
exit(-1);
}
count++;
}
//print final message
cout << "TID: " << pthread_self() << " worked on the buffer " << count << " times" << endl;
}
int main(int argc, char *argv[])
{
int num_threads = 3;
pthread_t *thread_ids;
void *p_status;
//Use unbuffered output on stdout
setvbuf(stdout, (char *) NULL, _IONBF, 0);
//Set up an output lock so that threads wait their turn to speak.
if (pthread_mutex_init(&output_lock, NULL)!=0)
{
perror("Could not create mutex for output: ");
return 1;
}
//Create 3 THREADS
thread_ids = new pthread_t[num_threads];
// generate threads
for (int i = 0; i < num_threads; i++)
{
int *arg = new int;
*arg = i;
if(pthread_create(&thread_ids[i],NULL,say_it,NULL) > 0)
{
perror("creating thread:");
return 2;
}
if (pthread_join(thread_ids[i], &p_status) != 0)
{
perror("trouble joining thread: ");
return 3;
}
}
return 0;
}
또한 프로그램 영역에 sleep (1)을 성공으로 설정하는 방법을 실험했습니다.
누구든지 나에게 설명 할 수 있습니까? 감사합니다.
'pthread_join' 스레드가 완료 될 때까지 기다립니다. 따라서 첫 번째 스레드가 주 스레드와 "결합"될 때까지는 두 번째 스레드를 생성하지 않습니다. – Anthony
복사 - 붙여 넣기 오류입니다 :''JOIN "'코드는''pthread_create'를 호출하고 생성 루프는''pthread_join'을 계속 호출합니다. – dasblinkenlight