#include <stdio.h>
#include <pthread.h>
void *foo (void *arg){
printf("Foobar!\n");
pthread_exit(NULL);
}
int main(void){
int i;
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSYEM);
pthread_create(NULL, &attr, foo, NULL);
return 0;
}
Compiling PThreads
1. #include
2. compile source with -lpthread or -pthread
Intro to OS ~ ==> gcc -o main main.c -lpthread
3. check return values of common functions
#include#include #define NUM_THREADS 4 void *hello (void *arg){ printf("Hello Thread\n"); return 0; } int main(void){ int i; pthread_t tid[NUM_THREADS]; for (i=0; i < NUM_THREADS; i++){ /* create/fork threads */ pthread_create(&tid[i], NULL, hello, NULL); } for (i=0; i < NUM_THREADS; i++){ pthread_join(tid[i], NULL); } return 0; }