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

Комментарии • 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 3 месяца назад +1

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

  • @ferstr3156
    @ferstr3156 3 года назад +8

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

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

  • @_denzy_6310
    @_denzy_6310 2 года назад

    Really like the vids. Useful for my project

  • @craigboger
    @craigboger 3 года назад

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

  • @fernandaeschallots2485
    @fernandaeschallots2485 2 года назад

    Your video is the best again. thx

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

  • @mohammedelboury4083
    @mohammedelboury4083 3 года назад

    Thank you , you explain very well

  • @navguest1740
    @navguest1740 3 года назад

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

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

  • @narasarajv5278
    @narasarajv5278 3 года назад

    Super explanation Thank you...

  • @siddharthpradeep
    @siddharthpradeep 2 года назад

    Thank you so much

  • @duanakshbandi6494
    @duanakshbandi6494 2 года назад

    never disappoints 😍👏

  • @kenomar
    @kenomar 3 года назад +1

    Thanks man !

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

  • @abhaygaikwad6251
    @abhaygaikwad6251 2 года назад

    understood

  • @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 Месяц назад

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

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

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

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

  • @DigitalAlligator
    @DigitalAlligator 2 года назад

    The University of RUclips...

  • @onaecO
    @onaecO 8 месяцев назад

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

    • @CodeVault
      @CodeVault  8 месяцев назад

      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.

  • @GamerWelfare
    @GamerWelfare Год назад

    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 11 месяцев назад

    what happens if we execute more threads than the number of cores(hardware or logical) we have?

    • @CodeVault
      @CodeVault  10 месяцев назад

      Some threads will start sharing the same core (or be paused) depending on the scheduler of your operating system

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

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

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

  • @VIVEKSHARMA-zx6uc
    @VIVEKSHARMA-zx6uc 10 месяцев назад

    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  10 месяцев назад

      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

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

  • @kamurashev
    @kamurashev Год назад

    👍

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

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

  • @RafQ321
    @RafQ321 3 года назад

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

    • @CodeVault
      @CodeVault  3 года назад

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

  • @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 года назад +1

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

  • @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 5 месяцев назад

    Man C is hard

  • @amparecircuit2405
    @amparecircuit2405 2 года назад

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

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