1.sleep(0)或者没有sleep
/* thread_test.c */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #define NUM_THREADS 4 pthread_mutex_t mutex; void *PrintHello(void *args) { int thread_arg; thread_arg = (int)(*((int*)args)); while(1) { // pthread_mutex_lock(&mutex); // thread_arg = (int)(*((int*)args)); // pthread_mutex_unlock(&mutex); if(1 == thread_arg) { printf("Hello from thread %d\n", thread_arg); } if(2 == thread_arg) { printf("Hello from thread %d\n", thread_arg); } sleep(0); } return NULL; } int main(void) { int rc,t; pthread_t thread[NUM_THREADS]; pthread_mutex_init (&mutex, NULL); for( t = 0; t < NUM_THREADS; t++) { printf("Creating thread %d\n", t); //此处t变量的用法是方便大家调测代码的写法,实际使用会有问题,因为这个t是局部变量, //函数执行完后马上释放,大家传递参数时需要使用全局变量或malloc出来的变量。 // 可写为 rc = pthread_create(&thread[t], NULL, PrintHello, (void*) t) // 在线程中,为thread_arg = (int)arg; rc = pthread_create(&thread[t], NULL, PrintHello, &t); if (rc) { printf("ERROR; return code is %d\n", rc); return EXIT_FAILURE; } } for( t = 0; t < NUM_THREADS; t++) pthread_join(thread[t], NULL); return EXIT_SUCCESS; }
编译命令:gcc thread_test.c -o thread_test -pthread
这种情况好像每次运行结果不同。有一次用sleep(0),最后只循环打印“Hello from thread 1”,thread 2抢不到cpu,一直没有打印;有一次没有用sleep,倒是打印一段时间的“Hello from thread 1”后再打印“Hello from thread 2”,thread1和thread2都能抢到cpu。
2.usleep(1)
一直交替打印“Hello from thread 1”和“Hello from thread 2”,基本上就是打印一次“Hello from thread 1”后接着再打印“Hello from thread 2”。
参考:
pthread_create_百度百科 (baidu.com)