# Posix threads in C


Differences between processes and threads

- Processes do not share their address space while threads are executed under the same process address space.
- Context switching is faster between threads than between processes.
- Threads can directly communicate (mutex, direct memory access) with other threads of its process but processes must use IPC (signals, semaphores, queues, shared memory) to communicate with other processes.

Code example

# cat threads_example.c
#include <pthread.h>
#include <stdio.h>

pthread_mutex_t pm;

void *inc_x(void *x_void_ptr){
        int *x_ptr=(int *)x_void_ptr;
        while(*x_ptr<10000){
                pthread_mutex_lock(&pm);
                        (*x_ptr)++;
                        printf("[+]x=%d\n",*x_ptr);
                pthread_mutex_unlock(&pm);
        }
        printf("x increment finished\n");
}

void *dec_x(void *x_void_ptr){
        int *x_ptr=(int *)x_void_ptr;
        while(*x_ptr>0){
                pthread_mutex_lock(&pm);
                        (*x_ptr)--;
                        printf("[-]x=%d\n",*x_ptr);
                pthread_mutex_unlock(&pm);
        }
        printf("x decrement finished\n");
}

int main(){
        int x=5000;
        pthread_t inc_x_thread;
        pthread_t dec_x_thread;
        printf("Initial x=%d\n",x);
        pthread_mutex_init(&pm,NULL);
        pthread_create(&inc_x_thread,NULL,inc_x,&x);
        pthread_create(&dec_x_thread,NULL,dec_x,&x);
        pthread_join(inc_x_thread,NULL);
        pthread_join(dec_x_thread,NULL);
        pthread_mutex_destroy(&pm);
        printf("Final x=%d\n",x);
        return 0;
}
# gcc -o threads_example threads_example.c -lpthread

No comments: