I am trying to create a multi-thread program that creates a thread for every file that is taken it (file1.txt to file20.txt) and I need to pass in a variable into the function using pthread_create
. I am having difficulties passing my int value into the function because pthread_create
only takes in void*
so my function has to take in a void*
.
I have some experience with pointers but I don't understand the concept of a void pointer very well. As far as I have been able to figure out is that my pthread_create
is suppose to look something simular to this pthread_create(&tids[i], NULL, getSales, (void*)i );
in main():
using namespace std;
int main(int argc, char **argv){
int numfiles = 20;
// Thread_ID's
pthread_t tids[numfiles];
// create threads
for(int i = 1; i <= numfiles; i++){
pthread_create(&tids[i], NULL, getSales, (void*)i );
}
// wait until threads are done
//join threads together so they run simultaneously
for(int i = 1; i <= numfiles; i++){
pthread_join(tids[i], NULL);
}
}
currently in getSales:
void* getSales(void* fileNum){
int* num = (int*)fileNum;
cout << &num <<endl;
pthread_exit(0);
}
currently when I compile this code it crashes and giving me multiple lines of back trace but it seems that the error is just the getSales function currently the output should print the numbers 1 to 20 in random order because the function is multi-threaded.
gcc staplemax.cpp -lpthread -o staplemax
staplemax.cpp: In function ‘int main(int, char**)’:
staplemax.cpp:114:57: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
pthread_create(&tids[i], NULL, getSales, (void*)i );
^
/tmp/ccf6zgpk.o: In function `getSales(void*)':
staplemax.cpp:(.text+0x10e): undefined reference to `std::cout'
staplemax.cpp:(.text+0x113): undefined reference to `std::ostream::operator<<(void const*)'
staplemax.cpp:(.text+0x118): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
edit:
I'm now compiling with g++ staplemax.cpp -lpthread -o staplemax
instead of gcc staplemax.cpp -lpthread -o staplemax
as recommended.
I also changed main due to it being pointed out that &i
was likely changed with the call of each loop of the for loop. my code currently looks like this
void* getSales(void* fileNum){
int num = *(int*)fileNum;
cout << num <<endl;
pthread_exit(0);
}
int main(int argc, char **argv){
int numfiles = 20;
// Thread_ID
pthread_t tids[numfiles];
int args[numfiles];
// create thread
for(int i = 0; i < numfiles; i++){
args[i] = i+1;
pthread_create(&tids[i], NULL, getSales, &args[i] );
}
// wait until thread is done //join
for(int i = 0; i < numfiles; i++){
pthread_join(tids[i], NULL);
}
}
This compiles (with g++
) but not all numbers are 1-20
3
2
9
1
10
6
87
5
4
11
12
13
14
15
16
17
18
19
20