My C knowledge is young, so forgive me 🙂 Two questions really,
-
How do I turn the following code into something that correctly makes use of
pthread_t *threadsArrayas opposed tothreadsArray[MAXCON]? -
Is there a good reason to? I’ve heard I should avoid using explicit arrays and try to use pointer defined arrays when I can.
pthread_t threadsArray[MAXCON];
int k;
for (k = 0; k < MAXCON; k++) {
fprintf(stderr, "Make %d\n", k);
int *connfd = malloc(sizeof(int));
*connfd = accept(fd, (struct sockaddr *) &cliaddr, &cliaddrlen);
if (*connfd == -1) {
perror("Unable to accept connection");
return 1;
}
fprintf(stderr, "Waited\n");
pthread_t thread;
pthread_create(&thread, NULL, readWriteToClient, connfd);
threadsArray[k] = thread;
}
for(k = 0; k < MAXCON; k++){
fprintf(stderr,"Join %d\n",k);
pthread_t thread = threadsArray[k];
pthread_join(thread, NULL);
}
To answer your second question first: it sounds like you’re talking about the different between stack and heap allocation.
Declaring the array in the function body like you’ve done will take up space on the stack, which can be quite limited (a few kilobytes to a few megabytes).
An alternative to this is to allocate the array on the “heap”, which is limited only by the available memory in your computer. To allocate memory on the heap, you use
malloc().So changing the first line to:
(and possibly checking for NULL if your system’s malloc can fail)
is all you need to do to allocate the array on the heap.
You’ll also need to do
free(threadsArray)afterwards to release the memory.But if MAXCON is small, allocating the array on the stack as you have done should be fine.