Download Introduction to C - Threads and more Summaries Programming Languages in PDF only on Docsity!
Introduction to C
Threads
Instructor: Yin Lou
Processes vs. Threads
Processes
I Multiple simultaneous
programs
I Independent memory space
I Independent open
file-descriptors
Threads
I Multiple simultaneous
functions
I Shared memory space
I Shared open file-descriptors
Threads
I One copy of the heap
I One copy of the code
I Multiple stacks
Threads
I One copy of the heap
I One copy of the code
I Multiple stacks
I Life Cycle
pthread
I #include <pthread.h>
I Define a worker function
pthread
I #include <pthread.h>
I Define a worker function
I void *foo(void *args) { }
pthread
I #include <pthread.h>
I Define a worker function
I void *foo(void *args) { }
I Initialize pthread attr t
I pthread attr t attr;
I pthread attr init(attr);
pthread
I #include <pthread.h>
I Define a worker function
I void *foo(void *args) { }
I Initialize pthread attr t
I pthread attr t attr;
I pthread attr init(attr);
I Create a thread
pthread
I #include <pthread.h>
I Define a worker function
I void *foo(void *args) { }
I Initialize pthread attr t
I pthread attr t attr;
I pthread attr init(attr);
I Create a thread
I pthread t thread;
I pthread create(&thread, &attr, worker function, arg);
I Exit current thread
pthread
I #include <pthread.h>
I Define a worker function
I void *foo(void *args) { }
I Initialize pthread attr t
I pthread attr t attr;
I pthread attr init(attr);
I Create a thread
I pthread t thread;
I pthread create(&thread, &attr, worker function, arg);
I Exit current thread
I pthread exit(status)
Thread Management
I pthread join(threadid, status)
I pthread detach(threadid)
Example
#include <stdio.h> #include <pthread.h> #define NUM_THREADS 5
void *print_hello(void *threadid) { long tid; tid = (long) threadid; printf("Hello World! It’s me, thread #%ld!\n", tid); pthread_exit(NULL); }
int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc; long t; for (t = 0; t < NUM_THREADS; t++) { printf("In main: creating thread %ld\n", t); rc = pthread_create(threads + t, NULL, print_hello, (void ) t); if (rc) { printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } / wait for all threads to complete */ for (t = 0; t < NUM_THREADS; t++) { pthread_join(threads[t], NULL); } pthread_exit(NULL); }
Compiling
I Use “-pthread”
Makefile
CC:=gcc
OPTIONS:=-O
LIB_PATH:=-pthread
SRC_DIR:=src
DST_DIR:=bin
default:
$(CC) $(OPTIONS) $(LIB_PATH) \
$(SRC_DIR)/*.c -o $(DST_DIR)/test
clean:
cd $(DST_DIR); rm test