如何创建存储Contentor结构体的10×10矩阵并为元素创建线程
Fixing Your 10x10 Contentor Matrix & Thread Handling Issues
Let's walk through the key problems in your code that are breaking matrix storage and thread behavior, then fix them step by step:
Critical Issues in the Original Code
- Mismatched Matrix Allocation: You can't assign a
mallocresult to a statically declared 2D array (struct Contentor parque[10][10]). Static arrays live on the stack, whilemallocgives heap memory — pick one approach. - Invalid String Assignment: Directly assigning string literals to char arrays with
= ""won't work in C. Usestrcpyormemsetto initialize/modify struct character arrays properly. - Wrong Thread Parameter: When creating threads, you're passing
1instead of a pointer to the targetContentorstruct. The thread function expects aContentor*, so this causes undefined behavior. - Backwards Empty Slot Check:
strcmp(parque[i][j].nSerie,"")returns 0 when strings are equal (empty). Your condition checks for non-zero, meaning you're treating occupied slots as free and vice versa. - Unseeded Random Numbers:
rand()uses a fixed seed by default, so you'll get the same delay sequence every run. Usesrand(time(NULL))to seed it for true randomness. - Sleep in the Wrong Place: Putting
sleep(randomNumber)in the main thread pauses the entire loop, not individual worker threads. The delay should happen inside the thread function. - Redundant Thread Attribute Setup: Reinitializing
pthread_attr_t attrinside the nested loop is inefficient — initialize it once outside the loop. - Invalid String Copy in Thread:
char destino[4] = arg_struct->porto;is invalid syntax for copying char arrays. Usestrcpyinstead.
Fixed Code Implementation
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <time.h> #include <unistd.h> struct Contentor { char nSerie[36]; char porto[4]; }; void* direcionaParaDestino(void* arg) { struct Contentor *contentor = (struct Contentor*) arg; // Safely copy the porto value char destino[4]; strcpy(destino, contentor->porto); // Generate random delay (0-4 seconds, max 5 total) int delay = rand() % 5; sleep(delay); // Process destination routing if(strcmp(destino, "ANR") == 0) { printf("Contentor %s routed to ANR after %d seconds\n", contentor->nSerie, delay); } else if (strcmp(destino, "BUS") == 0) { printf("Contentor %s routed to BUS after %d seconds\n", contentor->nSerie, delay); } else if (strcmp(destino, "DXB") == 0) { printf("Contentor %s routed to DXB after %d seconds\n", contentor->nSerie, delay); } else if (strcmp(destino, "GUA") == 0) { printf("Contentor %s routed to GUA after %d seconds\n", contentor->nSerie, delay); } else if (strcmp(destino, "HAM") == 0) { printf("Contentor %s routed to HAM after %d seconds\n", contentor->nSerie, delay); } else if (strcmp(destino, "HKG") == 0) { printf("Contentor %s routed to HKG after %d seconds\n", contentor->nSerie, delay); } else if (strcmp(destino, "LAX") == 0) { printf("Contentor %s routed to LAX after %d seconds\n", contentor->nSerie, delay); } else if (strcmp(destino, "RTM") == 0) { printf("Contentor %s routed to RTM after %d seconds\n", contentor->nSerie, delay); } else if (strcmp(destino, "SHA") == 0) { printf("Contentor %s routed to SHA after %d seconds\n", contentor->nSerie, delay); } else if (strcmp(destino, "SIN") == 0) { printf("Contentor %s routed to SIN after %d seconds\n", contentor->nSerie, delay); } else { printf("Contentor %s has unknown port %s\n", contentor->nSerie, destino); } pthread_exit(NULL); } int main() { // Seed random number generator for delays srand(time(NULL)); // Static 10x10 matrix (stack-allocated, simpler for your use case) struct Contentor parque[10][10]; // Initialize all slots to empty for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { memset(parque[i][j].nSerie, 0, sizeof(parque[i][j].nSerie)); memset(parque[i][j].porto, 0, sizeof(parque[i][j].porto)); } } // Example: Populate some slots with test data strcpy(parque[0][0].nSerie, "SERIE001"); strcpy(parque[0][0].porto, "LAX"); strcpy(parque[2][3].nSerie, "SERIE002"); strcpy(parque[2][3].porto, "HKG"); strcpy(parque[5][5].nSerie, "SERIE003"); strcpy(parque[5][5].porto, "SIN"); pthread_t tids[10][10]; pthread_attr_t attr; pthread_attr_init(&attr); // Explicitly set thread to joinable (default, but clear) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); // Create threads only for occupied slots for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { // Check if slot is occupied (nSerie is not empty) if(strcmp(parque[i][j].nSerie, "") != 0) { printf("Lugar [%d][%d] encontra-se Ocupado - creating thread\n", i, j); // Pass pointer to the specific Contentor struct int rc = pthread_create(&tids[i][j], &attr, direcionaParaDestino, &parque[i][j]); if(rc != 0) { fprintf(stderr, "Failed to create thread for [%d][%d]\n", i, j); exit(EXIT_FAILURE); } } else { printf("Lugar [%d][%d] encontra-se Livre\n", i, j); } } } // Clean up thread attributes pthread_attr_destroy(&attr); // Join only threads that were actually created for(int i = 0; i < 10; i++) { for(int j = 0; j < 10; j++) { if(strcmp(parque[i][j].nSerie, "") != 0) { pthread_join(tids[i][j], NULL); } } } printf("All threads completed processing\n"); return EXIT_SUCCESS; }
Key Improvements Explained
- Matrix Initialization: We use a static 10x10 array and initialize all char arrays with
memsetto ensure they start empty. - Proper String Handling: All string assignments use
strcpy, the correct method for copying into char arrays in C. - Correct Thread Parameters: We pass a pointer to the specific
Contentorstruct when creating threads, so the thread function can access its data safely. - Independent Thread Delays: The random delay is moved inside the thread function, so each thread waits on its own without blocking the main loop.
- Fixed Slot Check: We now correctly identify occupied slots with
strcmp(parque[i][j].nSerie, "") != 0. - Clean Attribute Management: Thread attributes are initialized once and destroyed after use for proper resource cleanup.
- Basic Error Checking: Added checks for
pthread_createfailures to catch issues early.
内容的提问来源于stack exchange,提问作者MyNameJeff
相关产品推荐
相关产品推荐

