0

今日、C プログラミングの本のプロセスとスレッドの章で、次のコード行に出くわしました。

printf("[Child]  child thread id: 0x%x\n", (unsigned int)pthread_self());

の部分は見たこと(unsigned int)pthread_self()がありません。最初の括弧のペアが何に使用されているかわかりません。何か案が?

PS:

php のドキュメントに、関数のドキュメントに同様の表現があることを覚えています。

int time()

しかし、実際のコードではtime()、 int の部分のみを使用して、ドキュメントの目的で関数の戻り値を表示しますtime()


アップデート:

各スレッド ID をテストする本のサンプル コードを入力します。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

int global = 5;

void* ChildCode(void* arg) {
    int local = 10;

    global++;
    local++; 
    printf("[Child]  child thread id: 0x%x\n", (unsigned int)pthread_self());
    printf("[Child]  global: %d  local: %d\n", global, local);

    pthread_exit(NULL);
}

int main() {
  pthread_t  childPid;
  int       local = 10;

    printf("[At start]  global: %d  local: %d\n", global, local);

  /* create a child thread */
  if (pthread_create (&childPid, NULL, ChildCode, NULL) != 0)
  {
    perror("create");
    exit(1);
  } else { /* parent code */
    global++;
    local--; 
    printf("[Parent] parent main thread id : 0x%x\n", (unsigned int)pthread_self());
    printf("[Parent] global: %d  local: %d\n", global, local);
    sleep(1);
  }
  printf("[At end] global: %d  local: %d\n", global, local);
  exit(0);
}

そして、それは私にいくつかのメモを与えます(エラーではなく警告ではありません):

clang example_thread.c 
/tmp/example_thread-9lEP70.o: In function `main':
example_thread.c:(.text+0xcc): undefined reference to `pthread_create'
clang: error: linker command failed with exit code 1 (use -v to see invocation)

コードがわかりません。

4

4 に答える 4

2

の戻り値pthread_self()はaですpthread_t(を参照man pthread_self)。

(unsigned int) pthread_self()の戻り値をpthread_self()符号なし整数にキャストするために使用されます。

Cでのキャストの詳細については、http://www.aui.ma/personal/~O.Ir​​aqi/csc1401/casting.htmを参照してください。

于 2012-08-07T09:53:31.290 に答える
1

これは、関数の戻り値をにキャストするだけunsigned intです。

それは次のようなものです:

pthread_t pthread_self_result;
pthread_self_result = pthread_self();
printf("[Child]  child thread id: 0x%x\n", (unsigned int)pthread_self_result);
于 2012-08-07T09:53:18.877 に答える
1

括弧はの戻り値をにキャストしていpthread_selfますunsigned intpthread_selfを返しますpthread_t。これは、での使用には適さない不特定の算術型ですprintf

于 2012-08-07T09:53:25.347 に答える
1

これは、Cでは「型キャスト」と呼ばれるものです。ここでは、pthread_t型をunsignedintにキャストして出力します。C言語のマニュアルを参照してください

于 2012-08-07T09:54:23.413 に答える