Linuxc语⾔sleep多线程while循环实验sleep(0)或者没有sleep
/* thread_test.c */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define    NUM_THREADS    16
pthread_mutex_t mutex;
void *PrintHello(void *args)
{
int thread_arg;
thread_arg = (int)(*((int*)args));
while(1)
linux下的sleep函数{
//  pthread_mutex_lock(&mutex);
//  pthread_mutex_unlock(&mutex);
if(1 == thread_arg)
{
printf("Hello from thread %d\n", thread_arg);
}
if(12 == 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);
rc = pthread_create(&thread[t], NULL, PrintHello, &t);
if (rc)
{
printf("ERROR; return code is %d\n", rc);
return EXIT_FAILURE;
}
sleep(1);
}
for( t = 0; t < NUM_THREADS; t++)
pthread_join(thread[t], NULL);
return EXIT_SUCCESS;
}
编译命令:gcc thread_test.c -o thread_test -pthread
打印⼀段时间的“Hello from thread 1”后再打印“Hello from thread 2”。
sleep(0)或者没有sleep,thread1和thread2都能抢到cpu。
测试环境是8核cpu。
thread 1和thread 12都能打印,8个cpu核都是100%使⽤。
似乎即使不⽤sleep,也不会⼀直占⽤cpu(导致线程间不能正常切换)。参考:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。