【发布时间】:2014-04-22 10:45:06
【问题描述】:
=)
我是这里的新用户,而且我是 C++ 新手,所以对我来说工作有点困难...... 所以我问你们一些问题! =)
我正在为学校做一项工作,要求我在其中实现线程优先级:
#include <pthread.h>
#include <stdio.h>
#include <sched.h>
int sched_yield(void);
// Parameters to print_function.
struct char_print_parms{
char character; // char to print
int count; // times to print
};
void* char_print (void* parameters){
int i;
struct char_print_parms* p;
p = (struct char_print_parms*) parameters;
for (i = 0; i < p->count; ++i){
fputc (p->character, stderr);
sched_yield();
}
return NULL;
}
int main (){
pthread_t thread1_id,thread2_id;
struct char_print_parms thread1_args,thread2_args;
// Create a new thread to print 200 x's.
thread1_args.character = 'x';
thread1_args.count = 200;
pthread_create (&thread1_id, NULL, &char_print, &thread1_args);
// Create a new thread to print 200 o's.
thread2_args.character = 'o';
thread2_args.count = 200;
pthread_create (&thread2_id, NULL,
&char_print, &thread2_args);
// main waits for the threads to complete
pthread_join(thread1_id, NULL);
pthread_join(thread2_id, NULL);
return 0;
}
这给出的是“oxoxoxo ...”等。
目标是获得更多的“o”,直到完成。
我所做的是:
#include <pthread.h>
#include <stdio.h>
#include <sched.h>
int sched_yield(void);
// Parameters to print_function.
struct char_print_parms{
char character; // char to print
int count; // times to print
};
void* char_print (void* parameters){
int i;
struct char_print_parms* p;
p = (struct char_print_parms*) parameters;
for (i = 0; i < p->count; ++i){
fputc (p->character, stderr);
sched_yield();
}
return NULL;
}
int main (){
pthread_t thread1_id,thread2_id;
struct char_print_parms thread1_args,thread2_args;
//new code lines
struct sched_param param;
pthread_attr_t pta;
pthread_attr_init(&pta);
pthread_attr_getschedparam(&pta, ¶m);
//end of new code lines
// Create a new thread to print 200 x's.
thread1_args.character = 'x';
thread1_args.count = 200;
//more new code lines
param.sched_priority = 0;
pthread_attr_setschedparam(&pta, ¶m);
pthread_setschedparam(thread1_id, SCHED_OTHER, ¶m);
//end of more new code lines
pthread_create (&thread1_id, NULL, &char_print, &thread1_args);
// Create a new thread to print 200 o's.
thread2_args.character = 'o';
thread2_args.count = 200;
//more new code lines 2
param.sched_priority = 10;
pthread_attr_setschedparam(&pta, ¶m);
pthread_setschedparam(thread2_id, SCHED_OTHER, ¶m);
//end of more new code lines 2
pthread_create (&thread2_id, NULL,
&char_print, &thread2_args);
// main waits for the threads to complete
pthread_join(thread1_id, NULL);
pthread_join(thread2_id, NULL);
return 0;
}
最后我编译并尝试运行,但出现错误:
分段失败(核心转储)
再一次,我是 C++ 新手,我的英语不是很好,但我想尝试理解为什么这不起作用。欢迎任何帮助!
【问题讨论】:
-
运行
gdb [yourprogram]并按r。然后它应该准确地告诉你哪里以及哪里出了问题。您可能必须使用-g选项编译您的程序。见gdb tutorial。 (从错误消息中我得出结论,您在 Unix 上使用 gcc,如果不是,请说明您使用的是什么。) -
@nwp 感谢您的帮助!我在 Ubuntu 上的 CodeBlocks 上运行此代码!它可以完成所有工作 =) 但是如果我不使用 CodeBlocks,我会做类似... 编译:gcc -c nchars.c 可执行文件:gcc -o nchars -lpthread nchars.o 它通常是我看到使用的(根据教授的说法…………)
标签: c++ multithreading thread-priority