簡體   English   中英

Linux,C:如何在32位操作系統中從大於4G的線程中獲得返回值?

[英]Linux, C: how can I get return value from thread which greate than 4G in a 32bits OS?

我正在運行32 bits操作系統。 現在,我創建的線程將返回一個int值,該值可能大於4G 如何通過pthread_join()main()函數接收此值? 看起來像在32 bits系統中, (void *)是4個字節。

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>

void* thread_function(void)
{
    uint64_t nbytes  = 0;
    //assign values to nbytes, it could be larger than 4G.
    return (void *)nbytes;
}

int main()
{
    pthread_t thread_id;
    uint64_t nbytes;

    pthread_create (&thread_id, NULL, &thread_function, NULL);
    pthread_join(thread_id,(void**)&nbytes); 
}

像這樣:

void* thread_function(void *)
{
    uint64_t nbytes  = 0;
    //assign values to nbytes, it could be larger than 4G.

    void *retval = malloc (sizeof (nbytes));
    memcpy (retval, &nbytes, sizeof (nbytes));
    return retval;
}

int main()
{
    pthread_t thread_id;
    uint64_t nbytes;

    pthread_create (&thread_id, NULL, &thread_function, NULL);

    void *ret;
    pthread_join(thread_id, &ret); 
    memcpy (nbytes, ret, sizeof (nbytes));
    free (ret);
}

這是將值從一個線程轉移到另一個線程的常見模式。 發送線程分配內存,復制值,並傳遞一個指針。 接收線程獲取指針,復制出值並釋放指針。

大衛·施瓦茲(David Schwartz)的解決方案是眾所周知的,但是傳遞一個簡單的整數實在太多了。 malloc()很昂貴,並且不一定是線程安全的(極不可能,但是今天有所有嵌入的東西……)。

提出OP的前兩個評論者的想法(WhozCraig和Eugene Sh。)

#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#include <stdlib.h>

void *thread_function(void *arg)
{
  /*
     No direct dereferencing
        *arg = 0xdeadbeefcafe;
     would give a compile error. With GCC it would be

     threadargs.c:8:5: warning: dereferencing ‘void *’ pointer [enabled by default]

  */
  uint64_t *nbytes = arg;
  *nbytes = 0xdeadbeefcafe;
  // you can return a simple status here, for example an error
  return 0;
}

int main()
{
  pthread_t thread_id;
  uint64_t nbytes;

  pthread_create(&thread_id, NULL, &thread_function, &nbytes);
  pthread_join(thread_id, NULL);
#define __STDC_FORMAT_MACROS
#include <inttypes.h>  
  printf("nbytes =  %" PRIx64 "\n", nbytes);

  return 0;
}

應該以另一種方式來完成這項工作,對於這種用法,也許是更好的選擇。

缺點:每個線程都希望填充自己的變量,因此它更適合固定數量的固定線程,否則您從堆分配內存,卻一無所獲,相反:保持狀態會更復雜關閉所有的malloc()/free() 在這種情況下,大衛·施瓦茲(David Schwartz)的方法更為恰當。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM