Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C threading in linux?

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?

like image 867
jahmax Avatar asked Jul 07 '10 19:07

jahmax


3 Answers

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;   
}
like image 161
Zifei Tong Avatar answered Sep 23 '22 05:09

Zifei Tong


The best option IMHO is to use POSIX threads. You can see more details HERE.

Also please check the link in James' answer.

like image 40
Incognito Avatar answered Sep 22 '22 05:09

Incognito


Search for POSIX threads, also known as pthreads. Tutorial Here

like image 20
James Avatar answered Sep 23 '22 05:09

James