I create some threads in a for loop and after this loop, join them in other loop. they do their function till all of them finish it,do they? my last result is logically wrong . my result is correct, just when join each thread after create it!!
Asked
Active
Viewed 1.1k times
1 Answers
2
Yes i think you are doing right.Letsee for example
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;
}
Its your decision when you want to exit that thread by calling pthread_exit function
.Absolutely there is no certainty that which thread will be executed first.Your OS will decide when resources are available for your threads and execute them on whatever CPU is least occupied

Ankur
- 3,584
- 1
- 24
- 32
-
thank you for answer very quick, I know it but there are no dependency between them. I write Gaussian elimination code and at each step just eliminate one arg of each row and my threads do this, when make zero all of one column make new thread for eliminate other arg of matrix.I think some of thread doesn't wait for join!! – user3416282 Dec 14 '14 at 12:11
-
@user3416282 Well you will not join threads that might be become undefined behaviour which is not desirable i guess.One thing you can do is to use GLOBAL COUNTING variable which will keep track whenever your row gets empty. – Ankur Dec 14 '14 at 12:14
-
my problem was that I have one arg for all new threads, so by change it for each thread, other one do their work wrong! thank you for your answer. – user3416282 Dec 14 '14 at 14:16