我正在做一个作业,该作业需要我使用线程来处理和同步从文件中获取数据。我的教授告诉我,我可以将数据更改为void指针,以将其传递给函数,然后将其投射回去。我正在尝试使用文件IO。
pthread_create(&th1, NULL, processing, (void *)&fp);
在我的处理函数中,我尝试使用以下命令将其投射回FILE指针:
FILE driveOne = (FILE *)file;
这显然行不通,所以有人可以向我解释一下吗?
答案 0 :(得分:0)
您需要将driveOne
声明为FILE *
,而不是FILE
。
FILE *driveOne = (FILE *)file;
此外,假设最初将fp
声明为FILE *
,则您对pthread_create
的调用在fp之前不应包含&,例如:
pthread_create(&th1, NULL, processing, (void *)fp);
答案 1 :(得分:0)
这是一个更完整的示例。
比方说,您的辅助函数需要文件句柄。为了简单起见,假设它从其中读取每个字符,然后返回读取的字符数,并转换为指针:
void *worker(void *data)
{
FILE *handle = (FILE *)data;
uintptr_t count = 0;
if (handle && !ferror(handle)) {
/* handle is a valid file handle */
while (getc(handle) != EOF)
count++;
}
return (void *)count;
}
如果count
是intptr_t
或uintptr_t
以外的其他类型(在<stdint.h>
中声明,通常包含在<inttypes.h>
中),则您d需要先将其转换为该类型,然后转换为空指针,即(void *)(uintptr_t)count
。
因为这样的工作线程不需要太多的堆栈(准确地说,几乎不需要),并且默认线程堆栈的大小很大(兆字节),所以我们可以节省一些内存(并且如果需要的话可以允许更多的线程,尤其是32个线程)位体系结构),方法是创建一个pthread属性,该属性指示pthread_create()
使用较小的堆栈。该属性不被调用“消耗”;它更像是一个配置块。
假设您有三个流FILE *in[3];
,并且您希望使用三个线程来检查它们的长度。使用pthread属性来使用较小的堆栈(2*PTHREAD_STACK_MIN
中定义的<limits.h>
对于不使用alloca()
或本地数组的工作线程来说是一个很好的安全值):
pthread_t worker_id[3];
uintptr_t length[3];
pthread_attr_t attrs;
void *retptr;
int i, result;
/* Create a pthread attribute set, defining smaller stack size. */
pthread_attr_init(&attrs);
pthread_attr_setstacksize(&attrs, 2*PTHREAD_STACK_MIN);
/* Create the three worker threads. */
for (i = 0; i < 3; i++) {
result = pthread_create(&(worker_id[i]), &attrs, worker, (void *)in[i]);
if (result) {
fprintf(stderr, "Cannot create thread: %s.\n", strerror(result));
exit(EXIT_FAILURE);
}
}
/* pthread attributes are no longer needed. */
pthread_attr_destroy(&attrs);
/*
... This thread can do something else here ...
*/
/* Reap the threads, and collect their return values. */
for (i = 0; i < 3; i++) {
result = pthread_join(worker_id[i], &retptr);
if (result) {
fprintf(stderr, "Cannot reap thread: %s.\n", strerror(result));
exit(EXIT_FAILURE);
}
length[i] = (uintptr_t)retptr;
}
for (i = 0; i < 3; i++)
printf("in[%d] contained %llu chars.\n", i, (unsigned long long)length[i]);
当您要将多个参数传递给线程函数时,可以使用相同的模式。首先,您要构造一个结构来保存这些参数,然后创建它们。您可以动态分配它们,将它们声明为全局变量,或者在main()中将它们声明为局部变量-在工作线程存在的整个时间内存在的任何作用域都起作用。
例如,假设您的辅助函数计算了从流中读取的每个unsigned char
值的直方图:
struct work {
pthread_t id; /* Thread identifier */
FILE *in; /* File handle to read from */
size_t count[UCHAR_MAX + 1]; /* Histogram */
};
void *worker(void *data) {
struct work *const work = (struct worker_data *)data;
int c;
if (!work || !work->in) {
/* Invalid data, or invalid file handle. */
return (void *)(intptr_t)(EINVAL);
}
if (ferror(work->in)) {
/* Stream is in error state. */
return (void *)(intptr_t)(EIO);
}
/* Read the stream. */
while ((c = getc(work->in)) != EOF) {
/* Update histogram. */
work->count[(unsigned char)c]++;
}
/* Did the reading stop due to an I/O error? */
if (ferror(work->in))
return (void *)(intptr_t)(EIO);
/* No errors, all done. */
return (void *)0;
}
请注意,struct work *const work = ...
会初始化常量指针work
,而不是指向常量的指针。 const
只是有一个优化,它告诉C编译器我们不会尝试修改work
指针本身。它指向的数据是可修改的。
(要读取指针声明,请从右到左读取它们,将每个*
替换为”是“ 的指针,以获得正确的含义。)
创建这些工作程序的代码非常相似,不同之处在于我们动态分配工作:
struct work *work[3];
pthread_attr_t attrs;
void *retptr;
int i, result;
/* Create and initialize the three pointers. */
for (i = 0; i < 3; i++) {
/* Allocate a work structure. */
work[i] = malloc(sizeof *(work[i]));
if (!work[i]) {
fprintf(stderr, "Out of memory.\n");
exit(EXIT_FAILURE);
}
/* Copy the handle to read from, */
work[i]->in = in[i];
/* and clear the histogram part. */
memset(work[i]->count, 0, sizeof work[i]->count);
}
/* Create a pthread attribute set, defining smaller stack size. */
pthread_attr_init(&attrs);
pthread_attr_setstacksize(&attrs, 2*PTHREAD_STACK_MIN);
/* Create the three worker threads. */
for (i = 0; i < 3; i++) {
result = pthread_create(&(work[i]->id), &attrs, worker, (void *)work[i]);
if (result) {
fprintf(stderr, "Cannot create thread: %s.\n", strerror(result));
exit(EXIT_FAILURE);
}
}
/* pthread attributes are no longer needed. */
pthread_attr_destroy(&attrs);
/*
... This thread can do something else here ...
*/
/* Reap the threads, and collect their return values. */
for (i = 0; i < 3; i++) {
result = pthread_join(work[i]->id, &retptr);
if (result) {
fprintf(stderr, "Cannot reap thread: %s.\n", strerror(result));
exit(EXIT_FAILURE);
}
/* If the thread reported a failure, print the corresponding
error message (but do not exit). */
if (retptr)
fprintf(stderr, "Thread %d of 3: %s.\n", i+1, strerror((intptr_t)retptr));
/* ... print the histogram here? ... */
}
/* Free the work structures. */
for (i = 0; i < 3; i++)
free(work[i]);
如果您不想在发生错误时中止程序,请注意free(NULL)
是安全的,并且不执行任何操作;并且struct work *pointerarray[SIZE] = {0};
声明了一个指向struct work
的SIZE指针数组,并将它们全部初始化为零。例如,如果某个分配或线程创建在某个时刻失败,则您可以free()
每个指针,无论其分配是否成功。
也就是说,如果您想分配三种不同类型的结构(struct atype *a;
,struct btype *b;
和struct ctype *c;
),则可以
a = malloc(sizeof *a);
b = malloc(sizeof *b);
c = malloc(sizeof *c);
if (!a || !b || !c) {
free(c);
free(b);
free(a);
return ALLOCATION_FAILED;
}
/* Allocation was successful */
而不是分别分配每个和测试失败。