【发布时间】:2016-03-16 16:17:59
【问题描述】:
我正在编写一个多线程网络程序。我需要声明一个 char 数组,以便两个线程都可以看到它。唯一的问题是我一开始不知道阵列会有多大,因为我必须等待网络上的另一台计算机告诉我。当我发现时,线程已经创建了。 sharedBuffer 的大小必须完全正确,这一点至关重要。
伪代码如下:
int bufSize;
char sharedBuffer[1]; //Ideally, sharedBuffer[bufSize]
//bufSize is not known yet, though.
//I don't know the best thing to declare here
int main(int argc, char* argv[]){
pthread_t ThreadA;
pthread_t ThreadB;
pthread_create(&ThreadA,0,&funcA,0);
pthread_create(&ThreadB,0,&funcB,0);
}
void *funcA(){
bufSize = getSize();//getSize implementation irrelevant, but working
//Small numbers expected. Probably no higher than 1024
//Initialize sharedBuffer here
sharedBuffer = realloc(sharedBuffer,bufSize*sizeof(char));
//Instinct tells me "sharedBuffer = new char[bufSize];"
// but I know C wont let me do that
//semaphore post
}
void *funcB(){
//semaphore wait (blocks until threadA posts)
printf("Size of shared buffer: %d\n",sizeof(sharedBuffer));
//needs to output bufSize
//actual value is irrelevant. Data just needs to be shared correctly.
}
编辑:更多信息,因为似乎没有人明白我的问题。我没有时间和信号量的问题。线程之间共享数据也没有问题。线程创建也没有问题。
我的问题是我不知道如何将共享缓冲区声明为数组类型,以便稍后可以由一个线程初始化,以便两个线程都可以使用它。我也不知道怎么初始化。
【问题讨论】:
-
数组不是指针(反之亦然)!
-
sizeof()产生一个未签名的size_t。一般来说,在不需要的情况下混合有符号 (int) 和无符号整数是一个坏主意。您应该在整个代码中使用size_t。 -
您可以永远在多线程应用程序中使用信号量,在线程之间共享公共内存。
-
@SergeyA:我猜
sem_init的联机帮助页是无用的:If pshared has the value 0, then the semaphore is shared between the threads of a process, and should be located at some address that is visible to all threads (e.g., a global variable, or a variable allocated dynamically on the heap).,因为你对“永远不会”如此确定。 -
@EOF,我说的是不同的信号量例程 - 由
semctl和朋友控制的信号量例程。
标签: c arrays multithreading