Does someone have a simple example of threading in c?
I want to build a small console app that will read a txt file file line by line and then use threads to process the entire txt. How should I do this? splitting the txt into X where X=N of threads, is the first thing that comes to my mind, is there a better way?
Search for pthreads. I'm also a thread newbie. Here is a code snippet to sum from 1 to 1000000000 (also my first working pthread program).
#include <stdio.h>
#include <pthread.h>
struct arg {
int a, b;
int *rst;
};
typedef struct arg arg;
void* sum(void *);
int main()
{
pthread_t sum1, sum2;
int s1, s2;
pthread_create(&sum1, NULL, sum, &(arg){1, 500000000, &s1});
pthread_create(&sum2, NULL, sum, &(arg){500000001, 1000000000, &s2});
pthread_join(sum1, NULL);
pthread_join(sum2, NULL);
printf("%d\n", s1 + s2);
}
void* sum(void *ptr)
{
int i, temp = 0;
arg *x = ptr;
for(i = x->a; i <= x->b; ++i)
temp += i;
*(x->rst) = temp;
}
The best option IMHO is to use POSIX threads. You can see more details HERE.
Also please check the link in James' answer.
Search for POSIX threads, also known as pthreads. Tutorial Here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With