2011-01-26 11 views
0

私は_beginthreadexを使ってcで新しいスレッドを作成しています。私は次のコードを書いています。 同じコードが2つのバージョンで書かれていますが、最初のバージョンは正常に動作していますが、2番目のバージョンは正常に動作していません。Cスレッドが正しく動作しない - シンプルコード

作業コード(下)

main.cの

#include <windows.h> 
#include <stdio.h> 

extern void func(unsigned (__stdcall *SecondThreadFunc)(void*)); 

int main() 
{ 
    func(NULL); 
} 

second.c

#include<Windows.h> 

//when thread start routine is declared in the same file new thread is running fine... 
//but if this routine is moved to main.c and passed as parameter to func new thread is not working 
unsigned __stdcall SecondThreadFunc(void* pArguments) 
{ 
    printf("In second thread...\n "); 
    return 0; 
} 


void func(unsigned (__stdcall *SecondThreadFunc)(void*)) 
{ 
    HANDLE hThread; 
    printf("Creating second thread...\n"); 

    // Create the second thread. 
    hThread = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0, NULL); 

    // Wait until second thread terminates. 
    WaitForSingleObject(hThread, INFINITE); 
} 

ない作業コード

main.cの

#include <windows.h> 
#include <stdio.h> 
#include <process.h> 


extern void func(unsigned (__stdcall *SecondThreadFunc)(void*)); 

unsigned __stdcall SecondThreadFunc(void* pArguments) 
{ 
    printf("In second thread...\n "); 
    return 0; 
} 

int main() 
{ 
    func(SecondThreadFunc); 
} 

second.c

#include<Windows.h> 

void func(unsigned (__stdcall *SecondThreadFunc)(void*)) 
{ 
    HANDLE hThread; 
    printf("Creating second thread...\n"); 

    // Create the second thread. 
    hThread = (HANDLE)_beginthreadex(NULL, 0, &SecondThreadFunc, NULL, 0, NULL); 

    // Wait until second thread terminates. 
    WaitForSingleObject(hThread, INFINITE); 
} 

SecondThreadFuncを呼び出している間、私は_beginthreadexの内側に、アクセス違反を取得しています。助けてもらえますか?前もって感謝します。あなたが持つべき機能していないコード(&のに注意を払う)で

+0

のprintf()などのstdio関数はスレッドセーフではありません。 – Lundin

答えて

1

hThread = (HANDLE)_beginthreadex(NULL, 0, SecondThreadFunc, NULL, 0, NULL); 
+0

はどちらも関数呼び出しですが、上記の修正が機能しているのはなぜですか? in c関数ポインタは関数を使用する必要はありません。あれは正しいですか? –

+0

@Vineel Kumar Reddy:あなたが述べた理由から、 'func()'呼び出しの変更は不要です。しかし、 'func()'の 'SecondThreadFunc'は関数ポインタの値なので、アドレスをとると関数のアドレスではなく関数ポインタのアドレスが得られます。この場合、 'SecondThreadFunc'と' * SecondThreadFunc'は同等の式です。 – caf

+0

うん、申し訳ありません。カフェの権利。私はそれを修正します。 – CAFxX

関連する問題