線程 pthread_join 函數返回 void * 出現 -Wpointer-to-int-cast 告警

最近學習多線程,寫Demo程序時,遇到一個編譯器告警,就是在用 pthread_join 函數獲取線程返回狀態值時,出現 -Wpointer-to-int-cast 告警。下面來看一下具體是啥問題

原 Demo 程序如下:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
void *func_1(void *);
void *func_2(void *);

int main() {
    pthread_t tid_1, tid_2;
    void *status;
    int err = pthread_create(&tid_1, NULL, func_1, NULL);
    assert(err == 0);
    err = pthread_create(&tid_2, NULL, func_2, NULL);
    assert(err == 0);
    
    err = pthread_join(tid_1, &status);
    assert(err == 0);
    printf("thread 1 exit status value is : %d\n", (int)status);
    err = pthread_join(tid_2, &status);
    assert(err == 0);
    printf("thread 2 exit status value is : %d\n", (int)status);
    return 0;
}
void *func_1(void *val) {
    pthread_t tid = pthread_self();
    printf("Thread 1: 0x%lx\n", (unsigned long)tid);
    return (void *)1;
}
void *func_2(void *val) {
    pthread_t tid = pthread_self();
    printf("Thread 2: 0x%lx\n", (unsigned long)tid);
    return (void *)2;
}

在用 gcc 編譯時,告警如下:
編譯器告警
分析原因:
先看下 pthread_join 函數原型如下:
int pthread_join(pthread_t thread, void **retval);

The pthread_join() function waits for the thread specified by thread to terminate.
If that thread has already terminated, then pthread_join() returns immediately.
The thread specified by thread must be joinable.

本人編譯環境是64位,gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04),函數 pthread_join 返回值爲 void * 類型大小 8 字節,在之後打印返回值 status 時,強制轉換爲 int (4 字節),故而產生該告警。

高版本gcc會產生編譯告警,程序可正常執行。但是低版本gcc(4.0)不會編譯告警,程序運行時會直接段錯誤 exit。
因此在使用 void * 做傳參時,一定要注意參數類型大小。

解決方式:打印返回值 status 時,強制轉換爲 long (8字節)即可。

修改的部分代碼:

err = pthread_join(tid_1, &status);
    assert(err == 0);
    printf("thread 1 exit status value is : %ld\n", (long)status);
    err = pthread_join(tid_2, &status);
    assert(err == 0);
    printf("thread 2 exit status value is : %ld\n", (long)status);

正常編譯後,運行如下:
運行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章