pthread_create()에 의해 호출되는 함수 인수가 여러 개입니까?
개별 스레드에서 호출하는 함수에 여러 인수를 전달해야 합니다.일반적인 방법은 구조를 정의하고 함수를 포인터로 전달하여 인수에 참조 해제하는 것이라고 읽은 적이 있습니다.그러나 이 기능을 사용할 수 없습니다.
#include <stdio.h>
#include <pthread.h>
struct arg_struct {
int arg1;
int arg2;
};
void *print_the_arguments(void *arguments)
{
struct arg_struct *args = (struct arg_struct *)args;
printf("%d\n", args -> arg1);
printf("%d\n", args -> arg2);
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t some_thread;
struct arg_struct args;
args.arg1 = 5;
args.arg2 = 7;
if (pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0) {
printf("Uh-oh!\n");
return -1;
}
return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}
이 경우의 출력은 다음과 같습니다.
5
7
하지만 실제로 실행해 보면 다음과 같은 것을 알 수 있습니다.
141921115
-1947974263
내가 뭘 잘못하고 있는지 아는 사람?
당신이 말했기 때문에
struct arg_struct *args = (struct arg_struct *)args;
대신
struct arg_struct *args = arguments;
사용하다
struct arg_struct *args = (struct arg_struct *)arguments;
대신해서
struct arg_struct *args = (struct arg_struct *)args;
오리지널 포스터 마이클과 같은 질문이 있습니다.
그러나 원래 코드에 대해 제출된 답변을 적용하려고 했지만 성공하지 못했습니다.
시행착오를 거듭한 후, 여기 내 버전의 코드가 있습니다(적어도 내게는 유효합니다).자세히 살펴보면 이전에 게시된 솔루션과는 다르다는 것을 알 수 있습니다.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct arg_struct
{
int arg1;
int arg2;
} *args;
void *print_the_arguments(void *arguments)
{
struct arg_struct *args = arguments;
printf("Thread\n");
printf("%d\n", args->arg1);
printf("%d\n", args->arg2);
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t some_thread;
args = malloc(sizeof(struct arg_struct) * 1);
args->arg1 = 5;
args->arg2 = 7;
printf("Before\n");
printf("%d\n", args->arg1);
printf("%d\n", args->arg2);
printf("\n");
if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
{
printf("Uh-oh!\n");
return -1;
}
return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}
용도:
struct arg_struct *args = malloc(sizeof(struct arg_struct));
그리고 이 인수를 다음과 같이 전달합니다.
pthread_create(&tr, NULL, print_the_arguments, (void *)args);
무료 아르그 잊지 마세요!;)
main()
자체 스레드 및 스택 변수가 있습니다.힙 내의 'syslogs'에 대해 메모리를 할당하거나 글로벌하게 만듭니다.
struct arg_struct {
int arg1;
int arg2;
}args;
//declares args as global out of main()
그럼 당연히 레퍼런스를 변경해 주세요.args->arg1
로.args.arg1
기타.
print_the_arguments의 args는 인수이므로 다음을 사용해야 합니다.
struct arg_struct *args = (struct arg_struct *)arguments.
struct arg_struct *args = (struct arg_struct *)args;
--> 이 할당은 잘못되어 있습니다.즉, 이 컨텍스트에서 변수 인수를 사용해야 합니다.건배!!!
이 코드의 스레드 생성에서는 함수 포인터의 주소가 전달되고 있습니다.오리지널pthread_create(&some_thread, NULL, &print_the_arguments, (void *)&args) != 0
라고 읽혀야 합니다.pthread_create(&some_thread, NULL, print_the_arguments, (void *) &args)
이 함수의 인수는 모두 주소여야 합니다.
some_thread
스태틱하게 선언되어 있기 때문에, 주소가 올바르게 송신됩니다.&
.
이 경우,pthread_attr_t
변수, 다음으로 사용pthread_attr_init()
그 변수의 주소를 넘겨줄 수 있습니다.하지만, 지나가고NULL
포인터도 유효합니다.
그&
기능 라벨 앞에 있는 것이 문제의 원인입니다.사용된 라벨은 이미void*
라벨만 있으면 됩니다.
말하다!= 0
결정되지 않은 행동을 일으킬 수 있습니다.이를 추가하면 참조가 아닌 부울이 전달되고 있음을 의미합니다.
Akash Agrawal의 답변도 이 코드 문제에 대한 해결책의 일부입니다.
같은 질문이지만 C++에 대해서는 중복으로 간주되므로 답변으로 C++ 코드를 제공하는 것이 좋을 것 같습니다.
// hello-2args.cpp
// https://stackoverflow.com/questions/1352749
#include <iostream>
#include <omp.h>
#include <pthread.h>
using namespace std;
typedef struct thread_arguments {
int thrnr;
char *msg;
} thargs_t;
void *print_hello(void *thrgs) {
cout << ((thargs_t*)thrgs)->msg << ((thargs_t*)thrgs)->thrnr << "\n";
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
cout << " Hello C++!\n";
const int NR_THRDS = omp_get_max_threads();
pthread_t threads[NR_THRDS];
thargs_t thrgs[NR_THRDS];
for(int t=0;t<NR_THRDS;t++) {
thrgs[t].thrnr = t;
thrgs[t].msg = (char*)"Hello World. - It's me! ... thread #";
cout << "In main: creating thread " << t << "\n";
pthread_create(&threads[t], NULL, print_hello, &thrgs[t]);
}
for(int t=0;t<NR_THRDS;t++) {
pthread_join(threads[t], NULL);
}
cout << "After join: I am always last. Byebye!\n";
return EXIT_SUCCESS;
}
다음 중 하나를 사용하여 컴파일 및 실행합니다.
g++ -fopenmp -pthread hello-2args.cpp && ./a.out # Linux
g++ -fopenmp -pthread hello-2args.cpp && ./a.exe # MSYS2, Windows
언급URL : https://stackoverflow.com/questions/1352749/multiple-arguments-to-function-called-by-pthread-create
'IT이야기' 카테고리의 다른 글
VUEX-STORE 모듈 이해 방법 (0) | 2022.06.06 |
---|---|
Vue 2 후크 준비 완료 (0) | 2022.06.06 |
문자열 변수 보간 Java (0) | 2022.06.05 |
time_t는 최종적으로 typedef는 무엇입니까? (0) | 2022.06.05 |
프로펠 변경 시 컴포넌트 업데이트 (0) | 2022.06.05 |