这是一个示例,其中读取线程与正在执行其他工作(在本例中为打印点和休眠)的“主”线程同时运行。
为了简单起见,我们通过逐个字符复制常量字符串来模拟输入设备的读取。我想,这是合理的,因为关注线程的同步。
对于线程的同步,我使用了atomic_bool 与atomic_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.'
$
我想,值得一提的是为什么在main() 和threadRead() 中使用的pBuffer 没有互斥保护。
pBuffer 在main() 中初始化之前 pthread_create() 被调用。
当thread_read() 运行时,pBuffer 被它独占使用(通过它在pPBuffer 中传递的地址)。
再次在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。