多线程的一个小例子

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <fcntl.h> #include <string.h> #define THNUM 5 pthread_mutex_t g_lock=PTHREAD_MUTEX_INITIALIZER; void* thr_fun(void* arg) { pthread_detach(pthread_self()); srand(pthread_self()); int fd=(int)arg; char buf[100]; memset(buf, 0, 100); sprintf(buf, "this is thread %x/n", (unsigned int)pthread_self()); pthread_mutex_lock(&g_lock); int ret=write(fd, buf, strlen(buf)); if( -1==ret ) { perror("write"); return NULL; } sleep(rand()%6+2); memset(buf, 0, 100); sprintf(buf, "this is thread %x/n", (unsigned int)pthread_self()); ret=write(fd, buf, strlen(buf)); if( -1==ret ) { perror("write"); return NULL; } pthread_mutex_unlock(&g_lock); return NULL; } int main(int argc, char *argv[]) { pthread_t tid[THNUM]; int i, ret; int fd=open("tmp", O_RDWR | O_CREAT | O_TRUNC, 0666); if( -1==fd ) { perror("open"); exit(1); } for( i=0 ; i<THNUM ; i++ ) { ret=pthread_create(tid+i, NULL, thr_fun, (void*)fd); if( ret!=0 ) { perror("pthread_create"); exit(1); } } pthread_exit(NULL); }

你可能感兴趣的:(多线程的一个小例子)