1 | #include<pthread.h> |
1 2 | int pthread_create(pthread_t *tidp, const pthread_attr_t *attr, ( void *)(*start_rtn)( void *), void *arg); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <string.h> void printids( const char *s) { pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf ( "%s pid %u tid %u (0x%x)\n" , s, (unsigned int ) pid, (unsigned int ) tid, (unsigned int ) tid); } void *thr_fn( void *arg) { printids( "new thread: " ); return NULL; } int main( void ) { int err; pthread_t ntid; err = pthread_create(&ntid, NULL, thr_fn, NULL); if (err != 0) printf ( "can't create thread: %s\n" , strerror (err)); printids( "main thread:" ); pthread_join(ntid,NULL); return EXIT_SUCCESS; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #define NUM_THREADS 8 void *PrintHello( void *args) { int thread_arg; sleep(1); thread_arg = ( int )(*(( int *)args)); printf ( "Hello from thread %d\n" , thread_arg); return NULL; } int main( void ) { int rc,t; pthread_t thread [NUM_THREADS]; for ( t = 0; t < NUM_THREADS; t++) { printf ( "Creating thread %d\n" , t); rc = pthread_create(& thread [t], NULL, PrintHello, &t); if (rc) { printf ( "ERROR; return code is %d\n" , rc); return EXIT_FAILURE; } } sleep(5); for ( t = 0; t < NUM_THREADS; t++) pthread_join( thread [t], NULL); return EXIT_SUCCESS; } |
联系客服