linux c thread
点击 1991 创建时间 2011-09-02 12:47:15
#include <pthread.h>
#include <stdio.h>
struct ThreadParam{ int name; };
void print_thread(struct ThreadParam *param )
{
int i;
for(i=0;i<5;i++ )
{
printf("thread name=%d", param->name );
usleep(10);
}
}
int main( int argc , char *argv[] )
{
struct ThreadParam param;
param.name=1;
pthread_t thread_id;
pthread_create( &thread_id , NULL , (void*)print_thread, ¶m );
printf("thread id:%d", (int)thread_id );
struct ThreadParam param2;
param2.name=2;
pthread_t thread_id2;
pthread_create( &thread_id2 , NULL , (void*)print_thread, ¶m2 );
printf("thread id:%d", (int)thread_id2 );
int i;
for( i=0; i< 5; i++ )
{
printf("main thread");
usleep(10);
}
pthread_join( thread_id, NULL );
pthread_join( thread_id2, NULL );
return 1;
}
output:
$ gcc thread.c -pthread -o thread && ./thread
thread id:-1215411344
thread id:-1223804048
main thread
thread name=2
thread name=1
main thread
thread name=2
thread name=1
main thread
thread name=2
thread name=1
main thread
thread name=2
thread name=1
main thread
thread name=2
thread name=1
$