博客專欄

        EEPW首頁 > 博客 > c++創建線程的常見問題:error: invalid conversion from 'void*' to 'void* (*)(void*)'

        c++創建線程的常見問題:error: invalid conversion from 'void*' to 'void* (*)(void*)'

        發布人:電子禪石 時間:2019-12-19 來源:工程師 發布文章

        重點:注意,這里只能寫gcc,究其原因就是C語言編譯器允許隱含性的將一個通用指針轉換為任意類型的指針,而C++不允許的。

        本人近期在做按tcp流發送數據包的學習,一來二去接觸到了多線程。我百度照此寫了個多線程代碼,如下:

        #include <pthread.h>
        #include <stdio.h>
        #include <stdlib.h>
        void thread(void *arg);
        void thread(void *arg)
        {
            int i;
            for(i = 0; i < 3; ++i){
                printf("This is a pthead.\n");
            }
        }
        int main(int argc, char* argv[])
        {
            pthread_t id;
            int i, ret;
            ret = pthread_create(&id, NULL, (void*)&thread, NULL);
            if(ret){
                printf("create thread error: ");
                exit(1);
            }
            for(i = 0; i < 3; ++i){
                printf("This is main proccess");
            }
            pthread_join(id, NULL);
            return 0;
        }
        但是,他爹,我用g++ main.cpp -o -lpthread debug進行編譯的時候,這個家伙:error: invalid conversion from 'void*' to 'void* (*)(void*)'不厭其煩地出現在了我的xshell中,弄得我是苦不堪言。
        于是,我查看了Posix中建立線程函數的定義:extern int pthread_create (pthread_t *__restrict __threadp,  __const pthread_attr_t *__restrict __attr, void(*__start_routine) (void *), void *__restrict __arg) __THROW;
        這個pthread_create()中的第三個參數是載入一個函數,這個函數有一個參數可以傳入,返回一個 通用指針。
        因此,出現上述錯誤的解決方法:
        1)線程函數定義為void  thread(void* arg),而調用處寫為:int ret = pthread_create(&id, NULL, (viod*)&thread, NULL);
        2)線程函數定義為void * thread(void* arg),調用處為:int ret = pthead_create(&id, NULL, thread, NULL)。
        然后進行編譯: gcc main.c -o -lpthread debug,搞定!
        注意,這里只能寫gcc,究其原因就是C語言編譯器允許隱含性的將一個通用指針轉換為任意類型的指針,而C++不允許的。
        ————————————————

        原文鏈接:https://blog.csdn.net/Alpelious/article/details/53486547


        *博客內容為網友個人發布,僅代表博主個人觀點,如有侵權請聯系工作人員刪除。

        電抗器相關文章:電抗器原理


        關鍵詞: c++

        相關推薦

        技術專區

        關閉
        主站蜘蛛池模板: 石景山区| 威远县| 大余县| 木兰县| 新泰市| 天峻县| 洛隆县| 涞源县| 镇坪县| 凤山市| 华蓥市| 嘉善县| 德惠市| 巴中市| 松阳县| 靖远县| 通山县| 阳泉市| 济南市| 玛纳斯县| 易门县| 唐山市| 固始县| 大埔县| 尚志市| 桦川县| 揭阳市| 东兰县| 都兰县| 苗栗县| 定州市| 永和县| 肃北| 湘西| 平塘县| 许昌市| 浑源县| 凌云县| 博罗县| 无锡市| 准格尔旗|