0
저는 pthreads에 익숙하지 않고 그것을 이해하려고합니다. 나는 하나의 스레드를 새로 생성하는 새로운 스레드를 만드는 프로그램을 작성했습니다 ... 그리고 threads_count! = 10; 배열로 스레드에 2 개의 매개 변수를 전달하고 싶습니다. 내가 main에서 호출하면 작동한다. 난 함수의 내부를 호출 할 때 나는 내가 잘못 새로운 스레드 기능의 내부에 인수를 전달스레드에서 배열 포인터가 어떻게 작동합니까?
Sleeping for 4 sec before thread creation
Sleeping for 32767 sec before thread creation
Sleeping for 28762 sec before thread creation
Sleeping for 28762 sec before thread creation
Sleeping for 28762 sec before thread creation
Sleeping for 28762 sec before thread creation
암과 같이된다? (이미 포인터의로) 그냥 thread_args
로 마지막 인수를 사용해야하는 동안 pthread_create(&t1, NULL, SpawnTwoThreads, &thread_args);
에서
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#define MAX_THREADS 10
int threads_count = 0;
void* SpawnTwoThreads(void *args) {
pthread_t t1;
pthread_t t2;
int* thread_args = (int*)args;
printf("Sleeping for %d sec before thread creation\n", thread_args[1]);
sleep(5);
if(threads_count < MAX_THREADS) {
threads_count++;
thread_args[1] = rand() % 10;
pthread_create(&t1, NULL, SpawnTwoThreads, &thread_args);
}
pthread_exit(NULL);
}
int main(void) {
pthread_t t1;
int t1_wait_time;
srand(time(NULL));
int start_args[2];
start_args[0] = 0;
start_args[1] = rand() % 10;
pthread_create(&t1, NULL, SpawnTwoThreads, &start_args);
printf("In main: waiting for all threads to complete\n");
pthread_join(t1, NULL);
printf("Overall waittime is %d\n", wait_time_overall);
pthread_exit(NULL);
}
로컬 변수에 대한 포인터를 전달하고 있는데이 함수는 함수가 반환 될 때 유효하지 않게됩니다. – Barmar
하지만 전역 변수로 만들면 세그먼트 화 오류가 발생합니다. –
모든 'thread_args'는 'main()'에서 나온 포인터와 같은 복사본이므로 모든 시간마다 'start_args [1]'을 (를) 덮어 쓰게됩니다. 'threads_count'의 증가분을 중심으로 뮤텍스 (mutex)를 사용해야합니다. – Barmar