Get return value from a thread (pthread_join)
HTML-код
- Опубликовано: 12 дек 2020
- Source code can be found here:
code-vault.net/lesson/18ec194...
===== Support us through our store =====
code-vault.net/shop
===== Check out our website =====
code-vault.net
===== Check out our Discord server =====
discord.code-vault.net
wow, I have a project on threads due in tonight and you just happen to release this video. You're amazing.
Can't stress enough how amazing your videos are: they've become a C Essentials+ Bible in our school, tyvm!
What I couldn't understand in one semester of OS I learned from you in a 9 min video
I can't write English, so I say it in spanish:
Gran video, amigo. Hace dos horas estaba buscando una solucion para retornar un valor. Solo con tu video pude lograrlo.
You have no idea how much you helped me with this video. Thank you :)
Great video. I was really struggling with this, but now it is much clearer:-). Thank you!
you really helped me dude, nice work and keep on doing this, you really rock!
Thankyou so much, you are helping me pass my final c assignment!!! Legend.
i am from France, i understands your explanation more than other videos in french, thanks 🙏🏽🙏🏽🙏🏽🙏🏽
U are a great explainer man, thanks a lot!!
thank you , a perfect example as usual
thanks, nice content from this got an idea of how to return values
Really like the vids. Useful for my project
Great video! Just had some segfaults on a school project and they did this very thing.
Your video is the best again. thx
I tried this code ... its better to add the free and int * res inside the join loop.... Thank you for these years ... I am one of your biggest fans ! ... I watched all of your videos since the beginnings and you made my life easy
Thank you , you explain very well
Keep doing great work :) waiting for the thread pool concept ....
yoo! That was a great video! Thanks ;)
Lmao I learned pointers from you and I guess I'm back to learn more again
Super explanation Thank you...
Thank you so much
never disappoints 😍👏
Thanks man !
Thx! you're awesome! :D
ty very much
Thanks for your effort!
Why do you not use deallocate memory in thread roll_dice?
Because we want to use it outside that function. If we free it in that function then we can't access it in the main function anymore
understood
Which video later in the playlist goes through using the "threads argument" that possibly solves allocating on the heap in one thread and deallocating the memory on the heap in the joining thread? Thanks!!
This one: code-vault.net/course/6q6s9eerd0:1609007479575/lesson/18ec1942c2da46840693efe9b51fb458
@@CodeVault Thank you!
Guessing pass the thread a block of memory and there's a mutex or some sort of resource handler when allocating the variable.
hey great vid! quick question, when you call pthread_create you pass in "&roll_dice", however passing in "roll_dice" also seems to work. Do they both mean the same thing?
Interesting, apparently there is absolutely no difference between &roll_dice and roll_dice. roll_dice will be considered &roll_dice because of the context
@@CodeVault I see. Thanks
Hey, I have a question. Is th considered to be a thread id or var name & are thread ids autogenerated? Can you please explain this topic along with pthread_self()? And thanks for your content!
Actually there's already a video that answers your question: code-vault.net/course/6q6s9eerd0:1609007479575/lesson/18ec1942c2da46840693efe9b5210e1b
@@CodeVault I watched it & this series is very helpful. Thank you so much for all the work you put into this ❤️
what extension are you using for debugging? like what should I install in order to get the Exception notice for seg fault in vs code?
There's an official C/C++ extension from Microsoft that I use
The University of RUclips...
Ty for the videos! i read that rand is not thread safe but i don't get why...
Basically, in the standard, the rand() function can use some internal state to return random numbers (depends on implementation). Because of this, calling it from multiple threads could cause a race condition of sorts.
I modified the 2 lines of code. The function returns this: "return result;" and pthread join looks like this "pthread_join(p1, (void *)&res)" and the program works the same way. Can you explain why?
Result is already a pointer and can be automatically casted to a void pointer without any issues. It's odd that you don't get any warning message at the pthread_join call but, really, pointer casting in C is not something that prevents you from building and running your code (pthread_join will still use the second argument as if it was a void**)
what happens if we execute more threads than the number of cores(hardware or logical) we have?
Some threads will start sharing the same core (or be paused) depending on the scheduler of your operating system
I tried implementing this for multiple threads using pthread_mutex_lock and pthread_mutex_unlock in the roll_dice() function. However I am a bit confused because I put two print statements in roll_dice() which I would think would print one after the other for each thread, however the print statements get a bit jumbled. Any advice on why this would happen?
void *roll_dice()
{
pthread_mutex_lock(&mutex);
int value = (rand() % 6) + 1;
int *result = malloc(sizeof(int));
*result = value;
printf("Thread pointer: %p
", result);
printf("thread result = %d
", *result);
pthread_mutex_unlock(&mutex);
return ((void *)result);
}
int main()
{
int *res;
int i;
srand(time(NULL));
pthread_t th[6];
i = 0;
while (i < 4)
{
if (pthread_create(th + i, NULL, &roll_dice, NULL) != 0)
return (-1);
i++;
}
i = 0;
while (i < 4)
{
if (pthread_join(th[i], (void **) &res) != 0)
return (-1);
free(res);
i++;
}
printf("Main res: %p
", res);
printf("Result: %d
", *res);
return (0);
}
What do you mean by "jumbled"?
@@CodeVault Hello! You're so fast. :) Below is an example of the output. But it's always different. I would think it would print "thread pointer", "thread result", "thread pointer", "thread result", etc... which it sometimes does but not always. And then there is the different pointer address in the beginning which is also strange.
Thread pointer: 0x7fcfbac05860
Thread pointer: 0x7fcfbae04080
Thread pointer: 0x7fcfbaf04080
thread result = 2
thread result = 6
Thread pointer: 0x7fcfbad04080
thread result = 6
thread result = 5
Main res: 0x7fcfbae04080
Result: 6
How would you return a vector of strings from a thread?
You'd probably need to have a struct for it with the number of strings and the pointer to that array, dynamically allocate it and return it. Although, since threads share their memory you could just store everything in some global part of memory
Please make videos on Semaphore and Mutex
Hey, there's one on mutex already: code-vault.net/lesson/18ec1942c2da46840693efe9b51eabf6
@@CodeVault then on semaphores and shared memory :D
How come malloc to *result assigned memory to *res. I understand that , thread uses same memory space. But how a pointer with different names worked.
Is it something like "pass by reference" and compiler connected them both,
as one is passed in pthread_join and other is returned. Is thats the reason both are given same memory
Ahh, because of the parameter passed to pthread_join. There, I pass &res which assigns the return value of the roll_dice function to res. We're not allocating any memory in the main thread, we're just getting the reference to the malloc'ed memory from each of the threads and then freeing it
what if pthread_t is a pointer say pthread_t *hello; hello = (pthread_t *) malloc(sizeof(hello); now how would give the parameter to pthread_join or pthread_cancel()? will it be pthread_join(*hello, NULL)?
Yeah, just like with any other pointer.
pthread_t* hello = malloc(sizeof(pthread_t));
...
pthread_create(hello, NULL, &function, NULL);
...
pthread_join(*hello, NULL);
free(hello);
Basically you just need to look at the signatures of the function. Since pthread_create takes in a pointer, you can simply pass that and in pthread_join you simply pass the value that hello points to.
👍
Can anyone please help me understand how does res point to result, was it done through pthread_join ? Also why did we only free the memory for res and not result at the end ?
1) Yes, the result from the roll_dice function is automatically assigned to the res we pass in pthread_join. We don't actually get a number but instead, pthread_join expects to get a pointer in return. This is important for your next question
2) In the main function we never assign anything to res (we never call malloc to allocate memory for it). What we get instead, after calling pthread_join is the pointer that we have allocated memory to inside the roll_dice function. So, inside roll_dice we allocate the memory (with malloc) and in the main function we deallocate it (with free)
@@CodeVault Thank you for taking the time to answer, this threading playlist has helped me immensely
What if I have to return an array of elements??
I tried many things but none is working, using join() it only returns the first element and then the program crashes...
I used a structure to pass arguments to the thread and to return the results ( instead of malloc() ).
Anyway, thanks for your videos! :)
The function pthread is using has the void* return type. So you can simply return the address to the array you want then it will be returned in join.
@@CodeVault I found out the problem..I needed to return an array of 10 elements and
In the Main I was using this for the returning array:
int* numbers[10];
Instead of:
int* numbers;
🙃
Thank you so much!
You could have cast the integer to void* directly
void *roll_dice(void *arg) {
int value = (rand() % 6) + 1;
return (void*)(unsigned long)value;
}
void *ret = NULL;
printf("Joined pthread %d with return value %lu
", i, (unsigned long)ret);
That's correct. It does feel like a workaround treating pointers as values and passing them around that's why I didn't want to use this in the video. Nonetheless, it's a quick way of passing data around if you know what you're doing!
Add in your shop "buy me a coffee" product ;)
Ahaha! I'll see what I can do ;)
res of main points to the result of function and result points to the value in the function
am i right??
Yea, basically. Except the value is not in the function, it's dynamically allocated.
@@CodeVault res(pointer of pointer) -> result(pointer) ->value. i think this can be better to describe what i mean. but anyway thx a lot. your video is so great ;-)
What if I need to return a struct?
Since it's a void pointer, you can return a pointer to a struct
i tried rolldice but every time i run it returns 6, how is it possible?
Where and how do you call srand()? I explain more about random numbers in this video: code-vault.net/lesson/9p823km0sm:1603733520459
@@CodeVault I am having the same result 6 every time. I call srand(time(NULL)); one time in main() create/join 10 threads that call roll_dice() function where I include (rand() % 6) + 1; if I comment out //srand(time(NULL)); I still get 10 6's (every time I ./a.exe). If I move srand(time(NULL)): into roll_dice(), then I get 10 of the same numbers but that number can range from 1 to 6 randomly every time I execute. Your videos and explanations are addicitive! Thank you!
Man C is hard
Sir please batao
Sigsegv thread -1.794849282
Kya matlab hai iska
In c programming
new update for python?
I'm not too experienced with Python, but I might take a look at it in the future
Shouldn't you have dereferenced res before sending to free? free(*res)? *res was malloced, not res. :)
No, res is the pointer pointing to the dynamically allocated memory that we created using malloc. Free requires the address to that memory, so free(res) is correct.
@@CodeVault Oh right, res is a pointer and you pass its address to the thread, so it's only double pointer in the thread. Man sometimes I think no matter how long I study C I will always misread pointer syntax! Good thing the compiler is there to set me straight. 😛
מעולה איך הוא מראה שאם מחזירים את המשתנה הלוקאלי כבר אסור להתייחס אליו כי הוא כבר לא קיים
I heard a robotic voice at 4:46. Are you actually a cyborg?