【发布时间】:2012-08-13 16:42:38
【问题描述】:
openmp 编译有问题。
如下代码:
#include <iostream>
#include <pthread.h>
#include <omp.h>
#include <semaphore.h>
#include <stack>
using namespace std;
sem_t empty,full;
stack<int> stk;
void produce(int i)
{
{
sem_wait(&empty);
cout<<"produce "<<i*i<<endl;
stk.push(i*i);
sem_post(&full);
}
}
void consume1(int &x)
{
sem_wait(&full);
int data=stk.top();
stk.pop();
x=data;
sem_post(&empty);
}
void consume2()
{
sem_wait(&full);
int data=stk.top();
stk.pop();
cout<<"consume2 "<<data<<endl;
sem_post(&empty);
}
int main()
{
sem_init(&empty,0,1);
sem_init(&full,0,0);
pthread_t t1,t2,t3;
omp_set_num_threads(3);
int TID=0;
#pragma omp parallel private(TID)
{
TID=omp_get_thread_num();
if(TID==0)
{
cout<<"There are "<<omp_get_num_threads()<<" threads"<<endl;
for(int i=0;i<5;i++)
produce(i);
}
else if(TID==1)
{
int x;
while(true)
{
consume1(x);
cout<<"consume1 "<<x<<endl;
}
}
else if(TID==2)
{
int x;
while(true)
{
consume1(x);
cout<<"consume2 "<<x<<endl;
}
}
}
return 0;
}
首先,我使用以下代码编译它:
g++ test.cpp -fopenmp -lpthread
而且,我得到了正确的答案,总共有 3 个线程。
但是,当我这样编译时:
g++ -c test.cpp -o test.o
g++ test.o -o test -fopenmp -lpthread
只有一个线程。
任何人都可以告诉我如何正确编译这段代码。提前谢谢你。
【问题讨论】:
-
我认为 OpenMP 编译指示会被忽略,除非您有
-fopenmp。因此,在所有具有 OpenMP 编译指示的模块上都需要-fopenmp。 -
@Mysticial 你认为我应该在将 .cpp 编译为 .o 文件时添加 -fopenmp 吗?
-
是的。试试
g++ -c test.cpp -o test.o -fopenmp。如果可行,我会给出答案。 -
@Mysticial 那是工作。非常感谢。
标签: c++ compilation g++ openmp