linux线程传递参数
linux-dash
A beautiful web dashboard for Linux
项目地址:https://gitcode.com/gh_mirrors/li/linux-dash
免费下载资源
·
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_THREADS 8
void *PrintHello(void *args)
{
int thread_arg;
sleep(1);
thread_arg = (int)(*((int*)args));
printf("Hello from thread %d\n", thread_arg);
return NULL;
}
int main(void)
{
int rc,t;
pthread_t thread[NUM_THREADS];
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(5);
for( t = 0; t < NUM_THREADS; t++)
pthread_join(thread[t], NULL);
return EXIT_SUCCESS;
}
有一点要特别注意,传递的变量地址最好是全局变量,或者加上sleep,这样可以保证线程启动接收到的参数地址有效
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define NUM_THREADS 8
void *PrintHello(void *args)
{
int thread_arg;
sleep(1);
thread_arg = (int)(*((int*)args));
printf("Hello from thread %d\n", thread_arg);
return NULL;
}
int main(void)
{
int rc,t;
pthread_t thread[NUM_THREADS];
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(5);
for( t = 0; t < NUM_THREADS; t++)
pthread_join(thread[t], NULL);
return EXIT_SUCCESS;
}
有一点要特别注意,传递的变量地址最好是全局变量,或者加上sleep,这样可以保证线程启动接收到的参数地址有效
GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e
added ecosystem file for PM2 4 年前
5def40a3
Add host customization support for the NodeJS version 4 年前
更多推荐
已为社区贡献11条内容
所有评论(0)