I want to create three threads and pass an integer to each of these thread. I used pthread_create, and my code is as follows.
#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
#define NUM_OF_JOB 3
void* doJob(void* arg){
int i = *((int*)arg);
printf("%d\n",i);
}
void init_job() {
pthread_t thread[NUM_OF_JOB];
int index[NUM_OF_JOB]={-1,-1,-1};
for(int i=0;i<NUM_OF_JOB;i++){
pthread_create(&thread[i],NULL,doJob,(void*)(&index[i]));
}
}
int main(){
init_job();
sleep(1);
return 0;
}
I intended to pass -1 to each of the thread, but after running the code for server times, I found that it did not print three -1. Instead, they could produce strange outputs. So why is that?
similar code can be found in pass arguments to the pthread_create function I can't find anything different between his code and mine. But in his code the threads could get the expected argument.
thank you very much:)
btw, I try to change the code from the above link a little, and run it.surprisingly, my mordified version don't produce expected results either.(I think each thread should get their own unique integer as argument) Here is my mordified code. can anyone explain that?
#include <stdio.h>
#include <pthread.h>
#define THREAD_NUM 10
void *thread_func(void *arg)
{
int v = *(int*)arg;
printf("v = %d\n", v);
return (void*)0;
}
int main(int argc, const char *argv[])
{
pthread_t pids[THREAD_NUM];
int rv;
int i;
for (i = 0; i < THREAD_NUM; i++) {
rv = pthread_create(&pids[i], NULL, thread_func, (void*)(&i));
if (rv != 0) {
perror("failed to create child thread");
return 1;
}
}
for (i = 0; i < THREAD_NUM; i++) {
pthread_join(pids[i], NULL);
}
return 0;
}
thank you again:)