저는 C++을 처음 접했고 스레드를 실험하고 있습니다. while 루프에서 스레드 안에 스레드를 만들려고합니다. 하지만 나는 그것이 작동하는 것 같지 않습니다. 는 현재 내 코드는 다음과 같습니다 : 내가 읽은해야하는 파일의 목록이 들어있는 파일을 읽을려고while 루프에서 다른 스레드 안에있는 스레드
#include <>
std::vector<pthread_t> outer_thread, inner_thread;
void *inner_thread(void *ptr)
{
string data1;
data1 = *(reinterpret_cast<string*>(ptr));
cout << "inner thread started " << data1;
/* do something */
cout << "inner thread stopped " << data1;
pthread_exit(NULL);
return 0;
}
void *outer_thread(void *ptr)
{
cout << "out thread started" << endl;
//cout << ptr << endl;
//cout << *(reinterpret_cast<string*>(ptr)) << endl;
string data;
data = *(reinterpret_cast<string*>(ptr));
string str3;
while (getline(data,str3))
{
cout << "out thread started" << endl;
pthread_t in_thread;
in_vec.push_back(str3);
int create_thread2 = pthread_create(&in_thread, NULL, &inner_thread, reinterpret_cast<void*>(&(in_vec.at(j))));
inner_thread.push_back(in_thread);
if (create_thread2 != 0)
cout << "Error : Thread";
j++;
cout << "out thread ends " << j << create_thread2 << endl ;
}
for (int k = 0; k < j ; k++)
{
pthread_join(inner_thread.at(k),NULL) ;
}
pthread_exit(NULL);
return 0;
}
int main (int argc, char *argv[])
{
int i = 0;
while (getline(gin,str))
{
string str1;
pthread_t out_thread;
cout << "str1" << str1 << endl;
now_vec.push_back(str1);
int create_thread = pthread_create(&out_thread, NULL, &outer_thread, reinterpret_cast<void*>(&(now_vec.at(i))));
outer_thread.push_back(out_thread);
if (create_thread != 0) cout << "Error : Thread" ;
i++;
}
for (int k = 0 ; k < i; k ++)
{
cout << i << endl;
//cout << "third thread " << outer_thread.at(1) << endl;
cout << outer_thread.at(k) << endl;
cout << "out out out" << endl;
pthread_join(outer_thread.at(k),NULL) ;
}
}
. 나는이 모든 파일을 동시에 읽고 싶다. 이러한 모든 파일에는 정보가 들어 있으며 다른 작업을 시작하기위한 또 다른 스레드 세트가 필요합니다. 따라서 이것은 동시에 수행되어야합니다. 그것이 2 개의 스레드 세트를 실행하는 이유입니다. 더 빠르고 간단한 방법이 있다면 알려주세요.
내부 스레드가 완료 될 때까지 기다렸다가 다음 반복으로 시작될 때까지 기다리는 것처럼 보입니다. 내부 스레드가 외부 스레드 내부에서 동시에 실행되기를 원합니다. 이것에 대해 어떻게 알아야할까요?
켭니다. 당신은 가치를 반환하지 않습니다. – chris
당신은 [pthread_join] (http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_join.html) * 루프 내부에 있습니다. 그래서 기다리고 있습니다. – jsantander
'pthread_t threads [i];'첫 번째 반복에서는 여기에 올바르게 할당하지 않습니다 ('int i = 0;'). –