Get return value from a thread (pthread_join)

แชร์
ฝัง
  • เผยแพร่เมื่อ 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

ความคิดเห็น • 91

  • @aaronshavolian1420
    @aaronshavolian1420 3 ปีที่แล้ว +30

    wow, I have a project on threads due in tonight and you just happen to release this video. You're amazing.

  • @fabiozucconi7068
    @fabiozucconi7068 5 หลายเดือนก่อน +1

    Can't stress enough how amazing your videos are: they've become a C Essentials+ Bible in our school, tyvm!

  • @LuisGuapo98
    @LuisGuapo98 3 ปีที่แล้ว +10

    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.

  • @rohanawasthi8387
    @rohanawasthi8387 2 ปีที่แล้ว +1

    You have no idea how much you helped me with this video. Thank you :)

  • @andychess
    @andychess ปีที่แล้ว +1

    Great video. I was really struggling with this, but now it is much clearer:-). Thank you!

  • @ionutsuteu9442
    @ionutsuteu9442 2 ปีที่แล้ว +1

    you really helped me dude, nice work and keep on doing this, you really rock!

  • @sleve_mcdichael
    @sleve_mcdichael 3 ปีที่แล้ว +1

    Thankyou so much, you are helping me pass my final c assignment!!! Legend.

  • @TheKunalingam
    @TheKunalingam 2 ปีที่แล้ว

    i am from France, i understands your explanation more than other videos in french, thanks 🙏🏽🙏🏽🙏🏽🙏🏽

  • @leobarros98
    @leobarros98 3 ปีที่แล้ว +2

    U are a great explainer man, thanks a lot!!

  • @Codality
    @Codality 2 ปีที่แล้ว +1

    thank you , a perfect example as usual

  • @nageshnikavade7712
    @nageshnikavade7712 3 ปีที่แล้ว

    thanks, nice content from this got an idea of how to return values

  • @craigboger
    @craigboger 3 ปีที่แล้ว

    Great video! Just had some segfaults on a school project and they did this very thing.

  • @_denzy_6310
    @_denzy_6310 2 ปีที่แล้ว

    Really like the vids. Useful for my project

  • @ferstr3156
    @ferstr3156 3 ปีที่แล้ว +8

    What I couldn't understand in one semester of OS I learned from you in a 9 min video

  • @mohammedelboury4083
    @mohammedelboury4083 3 ปีที่แล้ว

    Thank you , you explain very well

  • @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

  • @fernandaeschallots2485
    @fernandaeschallots2485 3 ปีที่แล้ว

    Your video is the best again. thx

  • @navguest1740
    @navguest1740 3 ปีที่แล้ว

    Keep doing great work :) waiting for the thread pool concept ....

  • @kenomar
    @kenomar 3 ปีที่แล้ว +1

    Thanks man !

  • @siddharthpradeep
    @siddharthpradeep 2 ปีที่แล้ว

    Thank you so much

  • @duanakshbandi6494
    @duanakshbandi6494 2 ปีที่แล้ว

    never disappoints 😍👏

  • @narasarajv5278
    @narasarajv5278 3 ปีที่แล้ว

    Super explanation Thank you...

  • @ale6025
    @ale6025 ปีที่แล้ว

    yoo! That was a great video! Thanks ;)

  • @josh1234567892
    @josh1234567892 2 ปีที่แล้ว +1

    Lmao I learned pointers from you and I guess I'm back to learn more again

  • @emmanuellazarte8904
    @emmanuellazarte8904 2 ปีที่แล้ว

    Thx! you're awesome! :D

  • @ezequielalegremendoza6612
    @ezequielalegremendoza6612 3 ปีที่แล้ว

    ty very much

  • @Blazic016
    @Blazic016 3 ปีที่แล้ว +1

    Thanks for your effort!
    Why do you not use deallocate memory in thread roll_dice?

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +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

  • @ozziekhoo
    @ozziekhoo 2 ปีที่แล้ว +1

    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  2 ปีที่แล้ว +1

      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 2 ปีที่แล้ว

      @@CodeVault I see. Thanks

  • @craigboger
    @craigboger 3 ปีที่แล้ว

    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  3 ปีที่แล้ว

      This one: code-vault.net/course/6q6s9eerd0:1609007479575/lesson/18ec1942c2da46840693efe9b51fb458

    • @craigboger
      @craigboger 3 ปีที่แล้ว

      @@CodeVault Thank you!

    • @user-io4sr7vg1v
      @user-io4sr7vg1v 3 หลายเดือนก่อน

      Guessing pass the thread a block of memory and there's a mutex or some sort of resource handler when allocating the variable.

  • @abhaygaikwad6251
    @abhaygaikwad6251 2 ปีที่แล้ว

    understood

  • @onaecO
    @onaecO 10 หลายเดือนก่อน

    Ty for the videos! i read that rand is not thread safe but i don't get why...

    • @CodeVault
      @CodeVault  9 หลายเดือนก่อน

      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.

  • @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

  • @dianafarhat9479
    @dianafarhat9479 ปีที่แล้ว

    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  ปีที่แล้ว +1

      Actually there's already a video that answers your question: code-vault.net/course/6q6s9eerd0:1609007479575/lesson/18ec1942c2da46840693efe9b5210e1b

    • @dianafarhat9479
      @dianafarhat9479 ปีที่แล้ว +1

      @@CodeVault I watched it & this series is very helpful. Thank you so much for all the work you put into this ❤️

  • @tongpoo8985
    @tongpoo8985 2 ปีที่แล้ว

    How would you return a vector of strings from a thread?

    • @CodeVault
      @CodeVault  2 ปีที่แล้ว

      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 2 ปีที่แล้ว

    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 2 ปีที่แล้ว

      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  2 ปีที่แล้ว

      What do you mean by "jumbled"?

    • @swaanmiller7710
      @swaanmiller7710 2 ปีที่แล้ว

      @@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

  • @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  ปีที่แล้ว

      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**)

  • @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

  • @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

  • @prashantpatil3088
    @prashantpatil3088 3 ปีที่แล้ว +2

    Please make videos on Semaphore and Mutex

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว

      Hey, there's one on mutex already: code-vault.net/lesson/18ec1942c2da46840693efe9b51eabf6

    • @xrufi
      @xrufi 3 ปีที่แล้ว

      @@CodeVault then on semaphores and shared memory :D

  • @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!

  • @Mnj3907
    @Mnj3907 2 ปีที่แล้ว

    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  2 ปีที่แล้ว

      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.

  • @notboredrn4181
    @notboredrn4181 ปีที่แล้ว

    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 ปีที่แล้ว

      @@CodeVault Thank you for taking the time to answer, this threading playlist has helped me immensely

  • @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 ปีที่แล้ว +1

      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!

  • @xernmottley9796
    @xernmottley9796 3 ปีที่แล้ว

    What if I need to return a struct?

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +1

      Since it's a void pointer, you can return a pointer to a struct

  • @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 ;-)

  • @RafQ321
    @RafQ321 3 ปีที่แล้ว

    Add in your shop "buy me a coffee" product ;)

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว

      Ahaha! I'll see what I can do ;)

  • @DigitalAlligator
    @DigitalAlligator 2 ปีที่แล้ว

    The University of TH-cam...

  • @kamurashev
    @kamurashev ปีที่แล้ว

    👍

  • @amparecircuit2405
    @amparecircuit2405 3 ปีที่แล้ว

    Sir please batao
    Sigsegv thread -1.794849282
    Kya matlab hai iska
    In c programming

  • @mattia2414
    @mattia2414 ปีที่แล้ว +1

    i tried rolldice but every time i run it returns 6, how is it possible?

    • @CodeVault
      @CodeVault  ปีที่แล้ว +1

      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!

  • @infamousstreaming2899
    @infamousstreaming2899 6 หลายเดือนก่อน

    Man C is hard

  • @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

  • @mikicerise6250
    @mikicerise6250 3 ปีที่แล้ว

    Shouldn't you have dereferenced res before sending to free? free(*res)? *res was malloced, not res. :)

    • @CodeVault
      @CodeVault  3 ปีที่แล้ว +1

      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 ปีที่แล้ว +1

      @@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. 😛

  • @bruslag
    @bruslag ปีที่แล้ว

    מעולה איך הוא מראה שאם מחזירים את המשתנה הלוקאלי כבר אסור להתייחס אליו כי הוא כבר לא קיים

  • @Mr-7ou6gn
    @Mr-7ou6gn 2 ปีที่แล้ว

    I heard a robotic voice at 4:46. Are you actually a cyborg?