c - 调用 pthread_join 函数后 main 不再继续

标签 c multithreading pthreads

我是 pthread 和多线程的新手,我已经编写了这样的代码。

#include <pthread.h>
#include <unistd.h>


void *nfc_read(void *arg)
{
    int fd = -1;   
    int ret;
    uint8_t read_data[24];

    while(1){
        ret = read_block(fd, 8, read_data);
        if(!ret){
            return (void)read_data;
        }
    }
}

int main(int argc, char *argv[])
{
    pthread_t my_thread;
    void  *returnValue;

    pthread_create(&my_thread, NULL, nfc_read, NULL);
    pthread_join(my_thread, &returnValue);

    printf("NFC card value is : %s \n", (char)returnValue);

    printf("other process");

  return 0;
}

直到nfc_read函数返回值,因为我还有其他需要运行的代码,并且我不想在main中阻塞。我怎样才能做到这一点?

最佳答案

这是一个示例,其中读取线程与正在执行其他工作(在本例中为打印点和休眠)的“主”线程同时运行。

为了简单起见,我们通过逐个字符复制常量字符串来模拟从输入设备的读取。我想,这是合理的,因为重点是线程的同步。

为了实现线程同步,我将 atomic_boolatomic_store()atomic_load() 一起使用,它们由 Atomic Library 提供。 (自 C11 起)。

我的示例应用程序test-concurrent-read.c:

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

/* sampe input */
const char sampleInput[]
  = "This is sample input which is consumed as if it was read from"
    " a (very slow) external device.";

atomic_bool readDone = ATOMIC_VAR_INIT(0);

void* threadRead(void *pArg)
{
  char **pPBuffer = (char**)pArg;
  size_t len = 0, size = 0;
  int c; const char *pRead;
  for (pRead = sampleInput; (c = *pRead++) > 0; sleep(1)) {
    if (len + 1 >= size) {
      if (!(*pPBuffer = realloc(*pPBuffer, (size + 64) * sizeof(char)))) {
        fprintf(stderr, "ERROR! Allocation failed!\n");
        break;
      }
      size += 64;
    }
    (*pPBuffer)[len++] = c; (*pPBuffer)[len] = '\0';
  }
  atomic_store(&readDone, 1);
  return NULL;
}

int main()
{
  /* start thread to read concurrently */
  printf("Starting thread...\n");
  pthread_t idThreadRead; /* thread ID for read thread */
  char *pBuffer = NULL; /* pointer to return buffer from thread */
  if (pthread_create(&idThreadRead, NULL, &threadRead, &pBuffer)) {
    fprintf(stderr, "ERROR: Failed to start read thread!\n");
    return -1;
  }
  /* start main loop */
  printf("Starting main loop...\n");
  do {
    putchar('.'); fflush(stdout);
    sleep(1);
  } while (!atomic_load(&readDone));
  putchar('\n');
  void *ret;
  pthread_join(idThreadRead, &ret);
  /* after sync */
  printf("\nReceived: '%s'\n", pBuffer ? pBuffer : "<NULL>");
  free(pBuffer);
  /* done */
  return 0;
}

在 Windows 10(64 位)上使用 cygwin 中的 gcc 进行编译和测试:

$ gcc -std=c11 -pthread -o test-concurrent-read test-concurrent-read.c

$ ./test-concurrent-read
Starting thread...
Starting main loop...
.............................................................................................

Received: 'This is sample input which is consumed as if it was read from a (very slow) external device.'

$ 

我想,值得一提的是为什么 pBuffer 没有互斥锁保护,它在 main() 以及 threadRead() 中使用.

  1. pBuffermain() 调用 pthread_create() 之前初始化。 p>

  2. thread_read()运行时,pBuffer被它独占使用(通过它在pPBuffer中传递的地址)。

  3. 再次在 main() 中访问它,但不在 pthread_join() 之前访问,这会授予 threadRead() 权限 已结束。

我试图通过谷歌找到引用资料来确认这个过程是明确定义和合理的。我能找到的最好的是 SO: pthread_create(3) and memory synchronization guarantee in SMP architectures其中引用了The Open Group Base Specifications Issue 7 - 4.12 Memory Synchronization .

关于c - 调用 pthread_join 函数后 main 不再继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44666733/

相关文章:

c - 谁在 C 的 Socket 上连接

c - C 中的子串垃圾

c# - Task.WaitAll 抛出 OperationCanceledException

java - 在登录方法上同步代码

C:线程之间的Fifo,写入和读取字符串

c - C 中 pthread 的线程函数计时问题

c - Arduino 与 A9 - AT 命令故障排除

c++ - MacOSx - 使用 make 命令编译 C 项目

multithreading - 如果ListView中有许多记录是从线程中添加的,则窗口会卡住

c - pthread_join 死锁的简单示例