我试图弄清楚为什么在我的代码中使用printf
如此奇怪。我将它与线程结合使用,老实说,我不知道为什么它不起作用。我使用互斥锁来确保一次只能有一个线程调用打印函数,并且该锁与将变量添加到列表(bbuff_blocking_insert
)的函数共享。到目前为止,这是我的代码:
#include "bbuff.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
typedef struct {
int num;
} car_t;
void *myThread(void* num) {
car_t *car = malloc(sizeof(int));
car->num = *(int*)num;
bbuff_blocking_insert(car);
// DEBUG
bbuff_print();
exit(0);
}
int main(int argc, char** argv) {
// Extract arguments //
int count = atoi(argv[1]);
// Initialize modules //
bbuff_init();
// Launch threads //
pthread_t tids[count];
pthread_attr_t attr;
pthread_attr_init(&attr);
int nums[count];
for (int i = 0; i < count; i++) {
nums[i] = i;
pthread_create(&tids[i], &attr, myThread, &nums[i]);
}
for (int i = 0; i < count; i++) {
pthread_join(tids[i], NULL);
}
exit(0);
}
这是bbuff.c文件
#include "bbuff.h"
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <string.h>
#include <pthread.h>
#define BUFFER_SIZE 10
sem_t empty;
sem_t full;
sem_t mutex;
void* bbuff[10];
void bbuff_init() {
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
sem_init(&mutex, 0, 1);
}
void bbuff_print() {
sem_wait(&mutex);
printf("Printing...\n");
for (int i = 0; i < BUFFER_SIZE; i++) {
if (bbuff[i] != NULL) {
car_t* car = (car_t*)bbuff[i]; // Convert void pointer to car pointer
printf("%d: %d\n", i, car->num);
}
else {
printf("%d: NULL\n", i);
}
}
sem_post(&mutex);
}
最后,如果我执行./a.out 3
,请在这里给出输出:
Printing...
0: 0
1: NULL
2: NULL
3: NULL
4: NULL
5: NULL
6: NULL
7: NULL
8: NULL
9: NULL
Printing...
0: 0
ing...
0: 0
还有另一个
./a.out 3
Printing...
0: 2
1: NULL
2: NULL
3: NULL
4: NULL
5: NULL
6: NULL
7: NULL
8: NULL
9: NULL
我希望它能像上面那样打印数组的表示形式,但是带有这样的内容:
./a.out 3
Printing...
0: 2
1: NULL
2: NULL
3: NULL
4: NULL
5: NULL
6: NULL
7: NULL
8: NULL
9: NULL
Printing...
0: 2
1: 0
2: NULL
3: NULL
4: NULL
5: NULL
6: NULL
7: NULL
8: NULL
9: NULL
Printing...
0: 2
1: 0
2: 1
3: NULL
4: NULL
5: NULL
6: NULL
7: NULL
8: NULL
9: NULL
感谢您的帮助,我知道这是一门值得学习的东西,所以对您的帮助都非常感谢!