1#include <assert.h> 2#include <stdlib.h> 3#include <stdio.h> 4#include <string.h> 5#include <signal.h> 6#include <unistd.h> 7#include <inttypes.h> 8#include <pthread.h> 9#include <sys/wait.h> 10#include <sched.h> 11 12void checked_write(int fd, const void *buf, size_t count) 13{ 14 ssize_t rc = write(fd, buf, count); 15 assert(rc == count); 16} 17 18void *thread1_func(void *arg) 19{ 20 int i; 21 char buf[512]; 22 23 for(i=0;i<10;i++) { 24 snprintf(buf, sizeof(buf), "thread1: %d %s\n", i, (char *)arg); 25 checked_write(1, buf, strlen(buf)); 26 usleep(100 * 1000); 27 } 28 return NULL; 29} 30 31void *thread2_func(void *arg) 32{ 33 int i; 34 char buf[512]; 35 for(i=0;i<20;i++) { 36 snprintf(buf, sizeof(buf), "thread2: %d %s\n", i, (char *)arg); 37 checked_write(1, buf, strlen(buf)); 38 usleep(150 * 1000); 39 } 40 return NULL; 41} 42 43void test_pthread(void) 44{ 45 pthread_t tid1, tid2; 46 47 pthread_create(&tid1, NULL, thread1_func, "hello1"); 48 pthread_create(&tid2, NULL, thread2_func, "hello2"); 49 pthread_join(tid1, NULL); 50 pthread_join(tid2, NULL); 51 printf("End of pthread test.\n"); 52} 53 54int main(int argc, char **argv) 55{ 56 test_pthread(); 57 return 0; 58} 59