[GNU/Linux]使用pthread库创建线程

#include <stdio.h>

// linux API / pthread
#include <unistd.h>
#include <pthread.h>

void  msleep(int ms)
{
    timespec ts;
    ts.tv_sec = ms / 1000;
    ts.tv_nsec = (ms % 1000) * 1000000;
    nanosleep(&ts, NULL);
}


// 线程入口函数
void* Thread_Main(void* context)
{
    while(1)
    {
        printf("i am a thread ...\n");
        //::sleep(1);
        msleep(100); // 500ms
    }
    return NULL;
}

// 
int main()
{
    // 创建线程(同时启动线程)
    pthread_t handle;
    if(pthread_create(&handle, NULL, Thread_Main, NULL) < 0)
    {
        printf("failed to create thread!\n");
        return -1;
    }
    
    getchar();
    return 0;
}

 

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注