[英]pthread_create argument in c multi thread programming
pthread_create(&Thread,NULL,ChildThread,(void *)100);
1)我們可以傳遞pthread_create的第4個參數,如上所示? 它不應該是指針變量嗎?
只是一個例子( not meant to be correct way of doing it; but to serve as example code for anyone who want to play with it
):
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <pthread.h>
void *print_number(void *number) {
printf("Thread received parameter with value: %d\n", number);
return (void *)number;
}
int main(int argc, char *argv[]) {
pthread_t thread;
void *ret;
int pt_stat;
pt_stat = pthread_create(&thread, NULL, print_number, (void *)100);
if (pt_stat) {
printf("Error creating thread\n");
exit(0);
}
pthread_join(thread, &ret);
printf("Return value: %d\n", ret);
pthread_exit(NULL);
return 0;
}
如果指針值大於int可以容納的值,這將導致未定義的行為。 從C99看到這個引用:
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.
What (void *)100
表示取整數值100並將其視為指向某些未指定類型的內存的指針(即(void *)
)。 在這種情況下,這意味着將堆棧上的整數值100作為pthread_create
的參數。 據推測, ChildThread
將傳遞給它的void *
轉換回int
,然后將其用作數字。
從根本上說,指針實際上只是內存地址。 內存地址只是一個描述內存中位置的數字,因此將int
轉換為任何類型的指針都是合法的。 在某些情況下,將int
轉換為指針絕對是正確的做法和要求,但是,它們往往很少見。 例如,如果您正在為嵌入式控制器編寫代碼,並且想要為內存映射I / O設備編寫驅動程序,那么您可以將設備的基址轉換為指向int或struct的指針,然后通過正常的C訪問來執行訪問設備的指針。 將int
轉換為指針的另一個例子是實現低級虛擬內存管理例程,以便為操作系統分配物理內存。
您提供的代碼並不常見,並且可以正常工作,假設指針的大小至少足以容納您嘗試傳遞的整數。 大多數實現pthread_create
系統可能都有32位或64位指針,因此您的示例很可能會起作用。 恕我直言,這有點濫用,因為在這種情況下100可能不會引用內存位置,並且C不保證void *
足以容納int
。
取自POSIX線程Progreamming的優秀artice 。 必須閱讀任何新手。
Example Code - Pthread Creation and Termination
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
}
說明:
您可以將100作為第4個參數傳遞給pthread_create()
。 在PrintHello函數中,您可以將void *轉換回正確的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.