Question

I need to know if I can store private data for a thread in the following way.

pthread_create(&threads[i], NULL, student, (void *) i);

void *student(void *arg) {
    int mybooks[3];
    int mybooks_index = 0;

    .......
}

Is this possible or is the only way of doing is sending a pointer to a struct as an argument when i create the thread?

Was it helpful?

Solution

Each thread has its own stack. mybooks and mybooks_index are automatic variables and thus allocated on the stack (i.e. per thread). They are only deallocated when student exits. So yes, this will work. If you had made them static, they would be shared between threads rather than be private to the thread.

OTHER TIPS

Yes. Each thread you spawn with an entry point of student will have their own copy of mybooks and mybooks_index. As noted by @WhozCraig, they are automatic variables.

What do you mean by storing private data in a thread like that ? Are you asking if mybooks array will be accessible in the "student" function? Yes it will be. Is this a good practice ? Depends on what you are trying to accomplish. I would suggest you to create a class for a book, called Book. Then you pass an object type of Book to the function that you are calling in the thread ( student() in your case ).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top