Practical example for using threads #1 (Summing numbers from an array)

preview_player
Показать описание
Source code can be found here:

===== Support us through our store =====

===== Check out our website =====

===== Check out our Discord server =====
Рекомендации по теме
Комментарии
Автор

You are such a humble genius who can deliver complex topics in the most crisp way possible.

benjaminschwartz
Автор

What a shame that these videos and the videos on process don't have a million views each.

HimanshuSharma
Автор

Nice, I did this without returning values but passing a struct containing two int arguments as the limits to traverse the array. And then a mutex helping for sums in a global variable.

joelkratos
Автор

Thanks a lot codevault. This playlist is gem <3

kaal_bhairav_
Автор

Thanks for the quality and efficient work.

vladimir_khlghatyan
Автор

*Thanks you again master, CodeVault.*

onurcanisler
Автор

The quality of these videos from a educational point of view is very high. Thanks for the content!
Since you are still making new videos one area where you can improve is the mic: if you listen to your videos with good headphones you will hear it that it's recording something like the sound of you putting your arms on the table (or something else) and this background noise distracts from the actual message. Hope this helps.

bjornnordquist
Автор

Recently came across your tutorials. Great work! You should package your tutorials and charge something. The quality is very good.
I have a question regarding this example. In an earlier video you were using mail++ in the thread function, and showed errors due to race conditions. Why are you not getting race conditions in this example? I would expect line 12, that reuses sum+= ... in both threads to suffer from race condition errors.

edwardprochon
Автор

Thank you much for creating such quality content <3

Ishowsciencee
Автор

Really nice content. Thanks a lot <3

balbeeryadav
Автор

Hello again.
I like to stop the video and try it on my own before I see your solution.
I've achieved again without using dynamic memory allocation.
I've done it by creating a 3-field "header" (like an IP header) in the threads array that I pass as an argument to the routine function:
The first field for the length of the header;
The second one for the length of the data (the number of threads);
And the last one for a pointer to another array in which each thread has to write its result.

I've done it so that the number of threads can be changed. In fact, in the code that I attached I have used 5 threads (the other divisor of 10).

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define nPrimes 10
int primes[nPrimes] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

void* primeSelect(pthread_t* argv)
{
int i = 0;
int match = 0;
int sum = 0;

int hLenth = argv[0];
int argc = argv[1];
int offSet = nPrimes / argc;
int* thRes = argv[2];

do
{
if(pthread_self() == argv[i+hLenth]) match = 1;
else i++;
}while(!match);

for(int j=offSet*i; j<((offSet*i)+offSet); j++) sum += primes[j];

thRes[i] = sum;

printf("ThID %d: %d\n", (long)pthread_self(), sum);
}

int main(int argc, char* argv[])
{
int totalSum = 0;

int hLenth = 3; //header length
int nTh = 5; //number of threads
int thRes[nTh]; //the threads are going to use this array to return its result

pthread_t th[nTh + hLenth];
th[0] = hLenth;
th[1] = nTh;
th[2] = thRes;

for(int i=hLenth; i<nTh+hLenth; i++) pthread_create(&th[i], NULL, &primeSelect, th);

for(int i=hLenth; i<nTh+hLenth; i++) pthread_join(th[i], NULL);

printf("\n");
for(int i=0; i<nTh; i++)
{
totalSum += thRes[i];
printf("Partial sum received by main: %d\n", thRes[i]);
}

printf("\n\tTotal sum: %d\n", totalSum);

return 0;
}

poincareelcartografo
Автор

@CodeVault Why a race condition is not happening in this particular case? Is it because the different threads are working on different chunks of memory?

arijitmondal
Автор

Im just measuring the posibility of implementing some web services I developed in Nodejs to C. C is a more neutral development enviroment so I may find some benefits. But Nodejs concurrrency approach is the event loop not threads. Nodejs non blocking approach seems more suitable for web servers. I found out some libraries in C++ that carry out an asynchronous approach. I wonder how good they are and how complicated woud be to adopt it.

petazeta
Автор

take routine function:
why can we not just use args instead of index inside the for loop for getting the sum?
so why we just don't do
sum += primes[*(int*)args + 1]
?

later edit: looks like is working too so maybe is just for improving readability.

raparaparapaDum
Автор

I'm really enjoying your videos. I have a question. Is the reason the sum inside the routine doesn't get a race condition is because each thread has its own stack? If the sum were a global variable, would it raise a race condition?

멋구
Автор

I have a query. If we have a string "aabcdeabc" and "abc", and our task is to count the number of occurrences of a substring in the string. If I use 3 threads and divide the longer string into 3 parts "aab", "cde", and "abc". Then, total count of substring using threads will be 1 however, there is 2 abc. How can we use threads to solve this issue in multithreading?

rabindrayadav
Автор

Thanks for the video. I have one doubt

*(int*)arg = sum;
return arg;

arg here is a pointer to void but we are type casting it to int* and returning the address of that, how is that possible?

shanthgaitonde
Автор

Nice, I got it! Is it possible without having the array as global variable?

mista_ia
Автор

Thank you, this video is very useful !
I know it's from two years ago but
I have a question : how can I do if I have an array of n rand elements (n entered by user) and I want m threads do the partial sum (m entered by user)?
trying my best but I have some problem with pointers😔

annaiandoli
Автор

How come you don't cast the variable "a" to void pointer inside of pthread_create function (line 25 when all the code is ready)? Just like you cast the address of the variable "r" to double void pointer inside of pthread_join function on line 32?

uygar
join shbcf.ru