【发布时间】:2014-03-03 15:12:33
【问题描述】:
我正在编写一个程序,它本质上是 UNIX 中“cp”命令的多线程版本。为此,我为输入/输出创建了文件,并初始化了信号量(分配所需)以同步共享数据。这是我的主要代码:
int main(int argc, const char * argv[])
{
//input/output file descriptors
int fdIn, fdOut;
//open files with proper rights
fdIn = open(argv[1], O_RDONLY);
fdOut = open(argv[2], O_WRONLY| O_CREAT | O_TRUNC, 0666);
//create and initialize semaphores
semaphore_t *empty = nullptr,*full = nullptr;
semaphore_create(mach_task_self(), empty, SYNC_POLICY_FIFO, 2);
semaphore_create(mach_task_self(), full, SYNC_POLICY_FIFO, 0);
//create and initialize structs to pass args to threads
threadDataConsumer.fd = fdOut;
threadDataConsumer.empty = empty;
threadDataConsumer.full = full;
threadDataProducer.fd = fdIn;
threadDataProducer.empty = empty;
threadDataProducer.full = full;
pthread_t tid1, tid2;
//create a thread for the producer and consumer
pthread_create(&tid1, NULL, Producer, (void *)&threadDataProducer);
pthread_create(&tid2, NULL, Consumer, (void *)&threadDataConsumer);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
我相信这就是我的问题所在,因为我什至还没有开始编写生产者和消费者线程。任何帮助表示赞赏。谢谢!
【问题讨论】:
-
段错误发生在哪里?
-
根据上面的代码,有很多地方可能会出现。甚至可能是没有传递足够的参数并且您正在尝试访问 argv[2]
-
我的建议,调试一下。尝试步入,跨过。最终你会自己找到它。`
标签: c multithreading unix