[英]Linux scheduling. (pthreads)
I'm trying to play around with threads and so far, with the code below, I'm doing fine. 我正在尝试使用线程,到目前为止,使用下面的代码,我做得很好。 I want also want to print the current index of the executing thread but I've encountered some problems.
我还想打印执行线程的当前索引,但是遇到了一些问题。
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *runner(void *param);
int main(int argc, char *argv[])
{
int i, policy;
pthread_t tid[NUM_THREADS];
pthread_attr_t attr;
pthread_attr_init(&attr);
if(pthread_attr_getschedpolicy(&attr, &policy) != 0)
fprintf(stderr, "Unable to get policy.\n");
else{
if(policy == SCHED_OTHER)
printf("SCHED_OTHER\n");
else if(policy == SCHED_RR)
printf("SCHED_RR\n");
else if(policy == SCHED_FIFO)
printf("SCHED_FIFO\n");
}
if(pthread_attr_setschedpolicy(&attr, SCHED_FIFO) != 0)
fprintf(stderr, "Unable to set policy.\n");
/* create the threads */
for(i = 0; i < NUM_THREADS; i++)
printf("Hi, I'm thread #%d\n", i);
pthread_create(&tid[i], &attr, runner, NULL);
/* now join on each thread */
for(i = 0; i < NUM_THREADS; i++)
pthread_join(tid[i], NULL);
}
/* Each thread will begin control in this function */
void *runner(void *param)
{
/* do some work... */
printf("Hello world!");
pthread_exit(0);
}
I'm trying to print the current executing thread along with "Hello world!". 我正在尝试打印当前正在执行的线程以及“ Hello world!”。 But, the output is this...
但是,输出是这个...
SCHED_OTHER
Hello, I'm thread #0
Hello, I'm thread #1
Hello, I'm thread #2
Hello, I'm thread #3
Hello, I'm thread #4
Segmentation fault (core dumped)
So far, I've already tried issuing 到目前为止,我已经尝试发行
ulimit -c unlimited
What can I tweak in the code to achieve my goal? 我可以对代码进行哪些调整以实现自己的目标?
This 这个
for(i = 0; i < NUM_THREADS; i++)
printf("Hi, I'm thread #%d\n", i);
pthread_create(&tid[i], &attr, runner, NULL);
should be 应该
for(i = 0; i < NUM_THREADS; i++) {
printf("Hi, I'm thread #%d\n", i);
pthread_create(&tid[i], &attr, runner, NULL);
}
In your code, you are just creating only one thread and attempting to join 5 threads. 在您的代码中,您仅创建一个线程并尝试加入 5个线程。
You forgot to put a block of statements in braces: 您忘了在大括号中放置一段语句:
for(i = 0; i < NUM_THREADS; i++)
printf("Hi, I'm thread #%d\n", i);
pthread_create(&tid[i], &attr, runner, NULL);
Multiple statements to be executed in for loop must be covered in braces otherwise only first of them is called, printf("Hi, I'm thread #%d\\n", i)
in this case. 在for循环中要执行的多个语句必须用大括号括起来,否则,只有第一个语句被调用,在这种情况下,
printf("Hi, I'm thread #%d\\n", i)
。 Solution: 解:
for(i = 0; i < NUM_THREADS; i++)
{
printf("Hi, I'm thread #%d\n", i);
pthread_create(&tid[i], &attr, runner, NULL);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.