Get return value from a thread (pthread_join)

  Рет қаралды 79,045

CodeVault

CodeVault

Күн бұрын

Пікірлер: 93
@aaronshavolian1420
@aaronshavolian1420 4 жыл бұрын
wow, I have a project on threads due in tonight and you just happen to release this video. You're amazing.
@fabiozucconi7068
@fabiozucconi7068 10 ай бұрын
Can't stress enough how amazing your videos are: they've become a C Essentials+ Bible in our school, tyvm!
@LuisGuapo98
@LuisGuapo98 3 жыл бұрын
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.
@ferstr3156
@ferstr3156 4 жыл бұрын
What I couldn't understand in one semester of OS I learned from you in a 9 min video
@rohanawasthi8387
@rohanawasthi8387 2 жыл бұрын
You have no idea how much you helped me with this video. Thank you :)
@SammanMahmoud
@SammanMahmoud 2 жыл бұрын
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
@TheKunalingam
@TheKunalingam 3 жыл бұрын
i am from France, i understands your explanation more than other videos in french, thanks 🙏🏽🙏🏽🙏🏽🙏🏽
@ionutsuteu9442
@ionutsuteu9442 2 жыл бұрын
you really helped me dude, nice work and keep on doing this, you really rock!
@sleve_mcdichael
@sleve_mcdichael 3 жыл бұрын
Thankyou so much, you are helping me pass my final c assignment!!! Legend.
@andychess
@andychess 2 жыл бұрын
Great video. I was really struggling with this, but now it is much clearer:-). Thank you!
@leobarros98
@leobarros98 4 жыл бұрын
U are a great explainer man, thanks a lot!!
@Codality
@Codality 2 жыл бұрын
thank you , a perfect example as usual
@josh1234567892
@josh1234567892 2 жыл бұрын
Lmao I learned pointers from you and I guess I'm back to learn more again
@craigboger
@craigboger 4 жыл бұрын
Great video! Just had some segfaults on a school project and they did this very thing.
@fernandaeschallots2485
@fernandaeschallots2485 3 жыл бұрын
Your video is the best again. thx
@_denzy_6310
@_denzy_6310 2 жыл бұрын
Really like the vids. Useful for my project
@nageshnikavade7712
@nageshnikavade7712 3 жыл бұрын
thanks, nice content from this got an idea of how to return values
@navguest1740
@navguest1740 4 жыл бұрын
Keep doing great work :) waiting for the thread pool concept ....
@ale6025
@ale6025 2 жыл бұрын
yoo! That was a great video! Thanks ;)
@prashantpatil3088
@prashantpatil3088 4 жыл бұрын
Please make videos on Semaphore and Mutex
@CodeVault
@CodeVault 4 жыл бұрын
Hey, there's one on mutex already: code-vault.net/lesson/18ec1942c2da46840693efe9b51eabf6
@xrufi
@xrufi 4 жыл бұрын
@@CodeVault then on semaphores and shared memory :D
@mohammedelboury4083
@mohammedelboury4083 3 жыл бұрын
Thank you , you explain very well
@Blazic016
@Blazic016 3 жыл бұрын
Thanks for your effort! Why do you not use deallocate memory in thread roll_dice?
@CodeVault
@CodeVault 3 жыл бұрын
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
@craigboger
@craigboger 4 жыл бұрын
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!!
@CodeVault
@CodeVault 4 жыл бұрын
This one: code-vault.net/course/6q6s9eerd0:1609007479575/lesson/18ec1942c2da46840693efe9b51fb458
@craigboger
@craigboger 4 жыл бұрын
@@CodeVault Thank you!
@JayDee-b5u
@JayDee-b5u 8 ай бұрын
Guessing pass the thread a block of memory and there's a mutex or some sort of resource handler when allocating the variable.
@narasarajv5278
@narasarajv5278 4 жыл бұрын
Super explanation Thank you...
@consumer9279
@consumer9279 Жыл бұрын
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);
@CodeVault
@CodeVault Жыл бұрын
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!
@GamerWelfare
@GamerWelfare 2 жыл бұрын
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?
@CodeVault
@CodeVault 2 жыл бұрын
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**)
@onaecO
@onaecO Жыл бұрын
Ty for the videos! i read that rand is not thread safe but i don't get why...
@CodeVault
@CodeVault Жыл бұрын
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.
@VIVEKSHARMA-zx6uc
@VIVEKSHARMA-zx6uc Жыл бұрын
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
@CodeVault
@CodeVault Жыл бұрын
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
@kenomar
@kenomar 3 жыл бұрын
Thanks man !
@ozziekhoo
@ozziekhoo 3 жыл бұрын
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?
@CodeVault
@CodeVault 3 жыл бұрын
Interesting, apparently there is absolutely no difference between &roll_dice and roll_dice. roll_dice will be considered &roll_dice because of the context
@ozziekhoo
@ozziekhoo 3 жыл бұрын
@@CodeVault I see. Thanks
@emmanuellazarte8904
@emmanuellazarte8904 3 жыл бұрын
Thx! you're awesome! :D
@dianafarhat9479
@dianafarhat9479 2 жыл бұрын
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!
@CodeVault
@CodeVault 2 жыл бұрын
Actually there's already a video that answers your question: code-vault.net/course/6q6s9eerd0:1609007479575/lesson/18ec1942c2da46840693efe9b5210e1b
@dianafarhat9479
@dianafarhat9479 2 жыл бұрын
@@CodeVault I watched it & this series is very helpful. Thank you so much for all the work you put into this ❤️
@mattia2414
@mattia2414 2 жыл бұрын
i tried rolldice but every time i run it returns 6, how is it possible?
@CodeVault
@CodeVault 2 жыл бұрын
Where and how do you call srand()? I explain more about random numbers in this video: code-vault.net/lesson/9p823km0sm:1603733520459
@probexpd1916
@probexpd1916 Жыл бұрын
@@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!
@JILLURRAHMANJIHAD
@JILLURRAHMANJIHAD 19 күн бұрын
you literally went for pthread exit() and suddenly like no not today
@desmondchan9439
@desmondchan9439 3 жыл бұрын
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?
@CodeVault
@CodeVault 3 жыл бұрын
There's an official C/C++ extension from Microsoft that I use
@l.d.wee589
@l.d.wee589 Жыл бұрын
what happens if we execute more threads than the number of cores(hardware or logical) we have?
@CodeVault
@CodeVault Жыл бұрын
Some threads will start sharing the same core (or be paused) depending on the scheduler of your operating system
@tongpoo8985
@tongpoo8985 3 жыл бұрын
How would you return a vector of strings from a thread?
@CodeVault
@CodeVault 3 жыл бұрын
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
@swaanmiller7710
@swaanmiller7710 3 жыл бұрын
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?
@swaanmiller7710
@swaanmiller7710 3 жыл бұрын
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); }
@CodeVault
@CodeVault 3 жыл бұрын
What do you mean by "jumbled"?
@swaanmiller7710
@swaanmiller7710 3 жыл бұрын
@@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
@Mnj3907
@Mnj3907 3 жыл бұрын
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)?
@CodeVault
@CodeVault 3 жыл бұрын
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.
@DigitalAlligator
@DigitalAlligator 2 жыл бұрын
The University of KZbin...
@notboredrn4181
@notboredrn4181 2 жыл бұрын
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 ?
@CodeVault
@CodeVault 2 жыл бұрын
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)
@notboredrn4181
@notboredrn4181 2 жыл бұрын
@@CodeVault Thank you for taking the time to answer, this threading playlist has helped me immensely
@siddharthpradeep
@siddharthpradeep 2 жыл бұрын
Thank you so much
@CinuzzuD
@CinuzzuD 3 жыл бұрын
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! :)
@CodeVault
@CodeVault 3 жыл бұрын
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.
@CinuzzuD
@CinuzzuD 3 жыл бұрын
​@@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; 🙃
@CinuzzuD
@CinuzzuD 3 жыл бұрын
Thank you so much!
@AlfadelAbdAlla-y8g
@AlfadelAbdAlla-y8g Ай бұрын
CAN YOU DO A VIDEO FOR POINTERS
@CodeVault
@CodeVault Ай бұрын
I might make one just for pointers in general
@m.preacher2829
@m.preacher2829 3 жыл бұрын
res of main points to the result of function and result points to the value in the function am i right??
@CodeVault
@CodeVault 3 жыл бұрын
Yea, basically. Except the value is not in the function, it's dynamically allocated.
@m.preacher2829
@m.preacher2829 3 жыл бұрын
@@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 ;-)
@xernmottley9796
@xernmottley9796 3 жыл бұрын
What if I need to return a struct?
@CodeVault
@CodeVault 3 жыл бұрын
Since it's a void pointer, you can return a pointer to a struct
@RafQ321
@RafQ321 4 жыл бұрын
Add in your shop "buy me a coffee" product ;)
@CodeVault
@CodeVault 4 жыл бұрын
Ahaha! I'll see what I can do ;)
@ezequielalegremendoza6612
@ezequielalegremendoza6612 4 жыл бұрын
ty very much
@Mr-7ou6gn
@Mr-7ou6gn 2 жыл бұрын
I heard a robotic voice at 4:46. Are you actually a cyborg?
@amparecircuit2405
@amparecircuit2405 3 жыл бұрын
Sir please batao Sigsegv thread -1.794849282 Kya matlab hai iska In c programming
@mikicerise6250
@mikicerise6250 3 жыл бұрын
Shouldn't you have dereferenced res before sending to free? free(*res)? *res was malloced, not res. :)
@CodeVault
@CodeVault 3 жыл бұрын
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.
@mikicerise6250
@mikicerise6250 3 жыл бұрын
@@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. 😛
@wiktor3599
@wiktor3599 2 жыл бұрын
new update for python?
@CodeVault
@CodeVault 2 жыл бұрын
I'm not too experienced with Python, but I might take a look at it in the future
@PHTM04
@PHTM04 Жыл бұрын
Man C is hard
@abhaygaikwad6251
@abhaygaikwad6251 2 жыл бұрын
understood
@bruslag
@bruslag 2 жыл бұрын
מעולה איך הוא מראה שאם מחזירים את המשתנה הלוקאלי כבר אסור להתייחס אליו כי הוא כבר לא קיים
@kamurashev
@kamurashev Жыл бұрын
👍
How to pass arguments to threads in C
13:52
CodeVault
Рет қаралды 84 М.
Practical example to barriers (pthread_barrier)
16:41
CodeVault
Рет қаралды 15 М.
The Best Band 😅 #toshleh #viralshort
00:11
Toshleh
Рет қаралды 22 МЛН
Сестра обхитрила!
00:17
Victoria Portfolio
Рет қаралды 958 М.
Introduction to semaphores in C
12:24
CodeVault
Рет қаралды 134 М.
Thread Pools in C (using the PTHREAD API)
22:54
CodeVault
Рет қаралды 45 М.
What is a mutex in C? (pthread_mutex)
9:18
CodeVault
Рет қаралды 174 М.
How to use realloc in C
11:56
CodeVault
Рет қаралды 10 М.
7 Outside The Box Puzzles
12:16
MindYourDecisions
Рет қаралды 153 М.
Practical example for pthread_mutex_trylock
13:12
CodeVault
Рет қаралды 16 М.
Producer - Consumer Problem in Multi-Threading
25:18
CodeVault
Рет қаралды 120 М.
What is pthread_exit?
6:20
CodeVault
Рет қаралды 19 М.