Linux c语言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)
    {
    //  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(导致线程间不能正常切换)。

参考:

pthread_create_百度百科 (baidu.com)


版权声明:本文为eidolon_foot原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。