Catalin Patulea | f71d612 | 2012-10-29 14:01:07 -0400 | [diff] [blame] | 1 | #include <assert.h> |
bellard | 1b6b029 | 2003-03-22 17:31:38 +0000 | [diff] [blame] | 2 | #include <stdlib.h> |
| 3 | #include <stdio.h> |
bellard | 7fb9a24 | 2003-04-11 00:13:04 +0000 | [diff] [blame] | 4 | #include <string.h> |
bellard | 1b6b029 | 2003-03-22 17:31:38 +0000 | [diff] [blame] | 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 | |
Catalin Patulea | f71d612 | 2012-10-29 14:01:07 -0400 | [diff] [blame] | 12 | void 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 | |
bellard | 1b6b029 | 2003-03-22 17:31:38 +0000 | [diff] [blame] | 18 | void *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); |
Catalin Patulea | f71d612 | 2012-10-29 14:01:07 -0400 | [diff] [blame] | 25 | checked_write(1, buf, strlen(buf)); |
bellard | 1b6b029 | 2003-03-22 17:31:38 +0000 | [diff] [blame] | 26 | usleep(100 * 1000); |
| 27 | } |
| 28 | return NULL; |
| 29 | } |
| 30 | |
| 31 | void *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); |
Catalin Patulea | f71d612 | 2012-10-29 14:01:07 -0400 | [diff] [blame] | 37 | checked_write(1, buf, strlen(buf)); |
bellard | 1b6b029 | 2003-03-22 17:31:38 +0000 | [diff] [blame] | 38 | usleep(150 * 1000); |
| 39 | } |
| 40 | return NULL; |
| 41 | } |
| 42 | |
| 43 | void 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 | |
| 54 | int main(int argc, char **argv) |
| 55 | { |
| 56 | test_pthread(); |
| 57 | return 0; |
| 58 | } |