我正在尝试编写一个程序,该程序将生成任意数量的线程,类似于我在 Convert a process based program into a thread based version? 中的代码,它使用进程来完成我想要完成的事情,到目前为止我有以下代码,我目前收到很多警告,但我真的想知道我是否正在接近我想要做的事情有点正确。
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void *runner(void *param); //the thread
int main(int argc, char *argv[]) {
pthread_t tid = gettid();
pthread_attr_t attr;
if (argc != 2){
fprintf(stderr, "Usage: a.out <integer value>\n");
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr, "Argument %d must be non negative\n", atoi(argv[1]));
return -1;
}
printf("My thread identifier is: %d\n", tid);
// default attributes
pthread_attr_init(&attr);
// create the thread
pthread_create(&tid, &attr, runner, argv[1]);
// wait for the thread to exit
pthread_join(tid, NULL);
}
void *runner(void *param){
//int i, upper = atoi(param);
int i;
srand48(gettid());
int max = nrand()%100;
if (max > 0){
for (i=1; i<=max; i++){
printf("Child %d executes iteration\n", param, i);
}
}
pthread_exit(0);
}
感谢我能得到的任何指导!
最佳答案
如果我理解您的目标,您希望创建命令行参数指示的线程数。
(请记住,任何特定操作系统只能支持固定数量的线程,这取决于操作系统,因此我不会在这里验证该数字的大小。)
以下建议代码:
- 干净地编译
- 执行所需的功能
- 记录了包含每个头文件的原因
- 检查从 C 库函数返回的错误指示,例如
pthread_create()
现在建议的代码:
#include <stdio.h> // printf(), perror(), NULL
#include <pthread.h> // pthread_create(), pthread_join(), pthread_t
#include <stdlib.h> // exit(), EXIT_FAILURE, atof()
void *runner(void *param); //the thread
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage: %s <integer value>\n", argv[0]);
exit( EXIT_FAILURE );
}
// might want to use: `strtol()` rather than `atoi()`
// so can check for errors
size_t maxThreads = (size_t)atoi(argv[1]);
pthread_t tid[ maxThreads ];
for( size_t i=0; i<maxThreads; i++ )
{
tid[i] = 0;
}
// create the threads
for( size_t i=0; i<maxThreads; i++ )
{
if( pthread_create( &tid[i], NULL, runner, (void *)i ) )
{
perror( "pthread_create failed" );
}
}
// wait for each thread to exit
for( size_t i = 0; i<maxThreads; i++ )
{
// if thread was created, then wait for it to exit
if( tid[i] != 0 )
{
pthread_join( tid[i], NULL );
}
}
}
void *runner(void *arg)
{
size_t threadNum = (size_t)arg;
printf( "in thread: %zu\n", threadNum );
pthread_exit( NULL );
}
不带命令行参数的运行结果:(其中可执行文件名为:untitled
Usage: ./untitled <integer value>
命令行参数为 10 的运行结果:
in thread: 0
in thread: 4
in thread: 2
in thread: 6
in thread: 1
in thread: 5
in thread: 7
in thread: 8
in thread: 9
in thread: 3
这清楚地表明线程的运行没有特定的顺序
关于c - 生成任意数量的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58829193/