0

I found a similar post pthread_create and passing an integer as the last argument however when implementing it I still receive the wrong ID values (as shown in the output log at the bottom of the post).

I have this portion of code which creates the threads. Its pretty standard. I have an array of threads which allocate a thread id which is passed into the function.

int nthreads = 7;
pthread_t tid[nthreads];

fprintf(stdout, "Creating threads.\n");
for (int i =0; i < nthreads; i++){
    tid[i] = i;
    if(pthread_create(&tid[i], NULL, threadRequestFile, &tid[i]) != 0){
        fprintf(stdout, "Error pthread_create().\n");
        steque_destroy(workerQueue);
        free(workerQueue);
        workerQueue = NULL;
        exit(EXIT_FAILURE);
    }
}
fprintf(stdout, "Created %d threads.\n", nthreads);

for(int i = 0; i < nthreads; i++){
    fprintf(stdout, "Awaiting Thread %d.\n", i);
    pthread_join(tid[i], NULL);
}

Finally my pointer function with has the ids stored in the address of tid[i] are passed into to print to the console:

void *threadRequestFile(void *nRequests){
    int totalRequests = * ((int *)nRequests);    
    fprintf(stdout, "Total Request: %d\n", totalRequests);
}

Unfortunately closely following the code in the post above and from other sources I found online, my console is still printing weird numbers rather than 0-6. Can anyone help me out as to why this is occurring?

Creating threads.
Total Request: -1210059008 // Should be 0
Total Request: -1218451712 // ..
Total Request: -1226844416 // ..
Total Request: -1235237120 // ..
Total Request: -1243629824 // ..
Total Request: -1252022528 // ..
Total Request: -1260415232 // 6
Created 7 threads.
Awaiting Thread 0.
Awaiting Thread 1.
Awaiting Thread 2.
Awaiting Thread 3.
Awaiting Thread 4.
Awaiting Thread 5.
Awaiting Thread 6.
Potion
  • 785
  • 1
  • 14
  • 36
  • Oh wow I can believe I overlooked this bit. I didnt realize first arg passed would be modified. Adding a new array fixed it. Thank you! (You can add it as an answer so I can accept it) – Potion Sep 18 '19 at 08:34
  • 1
    Note that the approach presented here is fundamentally different from the one in the question you linked. The other is about passing an integer by converting *the value itself* to a pointer and back. What you're doing here is passing *a pointer to the value* (and performing appropriate conversions on the pointer's type). Both are valid approaches in a general sense, but using *bona fide* pointers does mean multiple threads have access to the pointed-to objects. – John Bollinger Sep 18 '19 at 11:59

0 Answers0