for ループでいくつかのスレッドを作成し、このループの後、それらを他のループに結合します。彼らは全員がそれを終えるまで彼らの役割を果たしますね? 私の最後の結果は論理的に間違っています。作成後に各スレッドに参加するだけで、私の結果は正しいです!!
9342 次
1 に答える
2
はい、私はあなたが正しいことをしていると思います。たとえば、Letsee
extern "C"
{
#include <pthread.h>
#include <unistd.h>
}
#include <iostream>
using namespace std;
const int NUMBER_OF_THREADS = 5;
void * thread_talk(void * thread_nr)
{
//do some operation here
pthread_exit(NULL); //exit from current thread
}
int main()
{
pthread_t thread[NUMBER_OF_THREADS];
cout << "Starting all threads..." << endl;
int temp_arg[NUMBER_OF_THREADS] ;
/*creating all threads*/
for(int current_t = 0; current_t < NUMBER_OF_THREADS; current_t++)
{
temp_arg[current_t] = current_t;
int result = pthread_create(&thread[current_t], NULL, thread_talk, static_cast<void*>(&temp_arg[current_t])) ;
if (result !=0)
{
cout << "Error creating thread " << current_t << ". Return code:" << result << endl;
}
}
/*creating all threads*/
/*Joining all threads*/
for(int current_t = 0; current_t < NUMBER_OF_THREADS; current_t++)
{
pthread_join(thread[current_t], NULL);
}
/*Joining all threads*/
cout << "All threads completed." ;
return 0;
}
呼び出してそのスレッドを終了するときは、あなたの決定です。絶対pthread_exit function
に、どのスレッドが最初に実行されるかは確実ではありません。OS は、リソースがスレッドで利用可能になるタイミングを決定し、最も占有されていない CPU でそれらを実行します。
于 2014-12-14T11:51:05.280 に答える