2013-02-20 177 views
1

我是線程編程的新手。所以我對這個看似愚蠢的問題表示歉意。pthread_create與pthread_attr_setschedparam無法正常工作

我想創建一個POSIX線程使用pthread_create()使用pthread_attr_t。我想設置sched_priority值,並把它在attribute.The代碼粘貼如下:

#include <iostream> 
#include <cstring> 
#include <pthread.h> 
using namespace std; 

void* log(void* arg) 
{ 

    FILE *fp = fopen("/tmp/log.txt", "w+"); 
    if (fp != NULL) 
    { 
    fputs("Logging with Thread", fp); 
    } 
    else 
    { 
    cout <<"file pointer not created" << endl; 
    } 
    return 0; 
} 
int main(int argc, char** argv) 
{ 

    pthread_t th; 
    pthread_attr_t th_attr; 
    int policy; 
    struct sched_param thparam; 
    memset(&thparam, 0,sizeof(sched_param)); 
    int retval = pthread_attr_init(&th_attr); 
    if (0 != retval) 
    { 
    cout <<"Attribute initialization failed" << endl; 
    } 

    thparam.sched_priority = 10; 

    int ret1 = pthread_attr_setschedparam(&th_attr, &thparam); 
    if (0 == ret1) 
    { 
    cout <<"pthread_attr_setschedparam PASSED" << endl; 
    } 

int ret = pthread_create(&th, &th_attr, log, NULL); 
if (0 != ret) 
    { 
    cout <<"thread not created" << endl;  
    } 
else 
    { 
    cout <<"Thread created" << endl; 
    } 

    int retval1 = pthread_getschedparam(th, &policy, &thparam); 
    if (0 != retval1) 
    { 
    cout <<"Inside Main::pthread_getschedparam FAILED at start" << endl; 
    } 
    else 
    { 
    cout <<"Inside Main::priority: " << thparam.sched_priority << endl; 
    cout <<"Inside Main::sched policy: " << policy << endl; 
    } 
    pthread_join(th, NULL); 

    return (0); 
} 

我每次運行這個程序,線程被創建,但默認的優先級(15在我的情況)。由於我已將優先級設置爲10,因此應從10個優先級開始。我不明白爲什麼會發生這種情況。我打印的所有日誌消息都如預期的那樣,似乎沒有錯誤。 任何人都可以請指出我在代碼中做錯了什麼?

謝謝!

編輯:

我似乎找到了一個有趣的事兒。無法創建線程時設置的線程的優先級。但是我可以在線程創建後改變其優先級。我使用API​​ pthread_setschedparam來設置優先級。這次線程的優先級正確地改變了。仍然無法理解爲什麼會發生這種情況。

我還應該提到,我正在使用ARM arch的嵌入式系統。我還將調度程序策略設置爲SCHED_RR。

有人可以解釋爲什麼會發生這種情況嗎?

回答

0

你確定你看到了這個輸出嗎?

pthread_attr_setschedparam PASSED 

你是不是檢查pthread_attr_setschedparam通話的錯誤,我認爲它可能返回EINVAL,所以線程的優先級沒有改變。

Linux手冊頁宣稱函數總是成功,但是當我測試你的代碼時,這不是真的。

+0

是我收到** pthread_attr_setschedparam PASSED **在我的輸出。我還檢查了錯誤值'EINVAL == ret1'和'ENOTSUP == ret1'。它不顯示任何錯誤日誌。 – spanky 2013-02-21 04:17:09

+0

呵呵,那很奇怪,那就失敗了。我看到這個通話失敗,所以想知道這是不是你所得到的,並且沒有注意到PASSED輸出的缺失,但它一定是其他的東西 – 2013-02-21 09:32:37

+0

我已經用我看到的新行爲編輯了這個問題。你有任何解釋。 – spanky 2013-02-21 09:37:20

0

嘗試這樣:

pthread_attr_init(&thread_attr); 
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED); 
+0

但我想創建具有某些屬性的線程。分離線程如何幫助我?您能否更加細緻。 – spanky 2013-02-22 04:25:12

0

從手冊頁:

In order for the parameter setting made by 
    pthread_attr_setschedparam() to have effect when calling 
    pthread_create(3), the caller must use 
    pthread_attr_setinheritsched(3) to set the inherit-scheduler 
    attribute of the attributes object attr to PTHREAD_EXPLICIT_SCHED. 
+0

雖然代碼是讚賞的,它應該總是有一個附帶的解釋。這並不需要很長時間,但它是可以預料的。 – peterh 2015-11-10 18:05:22