FAIRYFAR-INTERNAL
 
  FAIRYFAR-INTERNAL  |  SITEMAP  |  ABOUT-ME  |  HOME  
您的足迹: pthread创建线程实例
pthread创建线程实例

代码

snippet.c
// 编译方法:gcc cg_test.c -lpthread -o cg_test
 
#include <sys/syscall.h>
#include <stdio.h>
#include <pthread.h>
 
typedef struct thread_arg
{
    int num;
} thread_arg;
 
void *my_thread_func(void* arg)
{
    thread_arg* thd_arg = (thread_arg*)arg;
 
    pid_t lwpid = syscall(SYS_gettid);
    printf("[%d] New thread created. LWPID: %d\n", thd_arg->num, lwpid);
 
    while (1)
    {
        usleep(2);
    }
 
    return NULL;
}
 
#define THD_NUM 2
 
int main()
{
    pid_t pid = getpid();
    pid_t lwpid = syscall(SYS_gettid);
    printf("[M] Main thread. PID: %d, LWPID: %d\n", pid, lwpid);
 
    pthread_t tids[THD_NUM];
    thread_arg args[THD_NUM];
 
    int i = 0;
    for (i = 0; i < THD_NUM; ++i)
    {
        args[i].num = 0;
        int ret = pthread_create(&tids[i], NULL, (void*)my_thread_func, &args[i]);
        if (ret)
        {
            printf("Create thread error!\n");
            return 1;
        }
    }
 
    for (i = 0; i < THD_NUM; ++i)
    {
        pthread_join(tids[i], NULL);
    }
 
    return 0;
}

编译

snippet.bash
[yz@yz219 ~]$ gcc test.c -lpthread -o test

运行

snippet.bash
[yz@yz219 ~]$ ./test 
[M] Main thread. PID: 9806, LWPID: 9806
[0] New thread created. LWPID: 9807
[0] New thread created. LWPID: 9808


打赏作者以资鼓励:
移动端扫码阅读:
目录: