我很新的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;')。 –