我想从这个网站运行示例46.3的变体http://theboostcpplibraries.com/boost.lockfree。我使用的是linux系统。
我想在头文件中定义队列q。我想有生产和消费功能是在不同的文件。所以我想让global。h包含
static boost::lockfree::queue<int> q{100};
static std::atomic<int> sum{0};
void *produce (void*);
void *consume (void*);
我想有一个product .cpp包含:
void *produce( void*)
{
for (int i = 1; i <= 10000; ++i)
q.push(i);
}
和我想有一个消费。cpp包含
void *consume (void*)
{
int i;
while (q.pop(i))
sum += i;
}
我想让我的main.cpp包含
#include iosteam
#include iomanip
#include global
#include pthread
int main ()
{pthread_t t1;
pthread_t t2;
pthread_t t3;
int t1_iret;
t1_iret = pthread_create( &t1, NULL, produce, NULL);
if(t1_iret)
{
fprintf(stderr,"Error - pthread_create() return code: %dn",t1_iret);
exit(EXIT_FAILURE);
}
int t2_iret;
t2_iret = pthread_create( &t2, NULL, consume, NULL);
if(t2_iret)
{
fprintf(stderr,"Error - pthread_create() return code: %dn",t2_iret);
exit(EXIT_FAILURE);
}
int t3_iret;
t3_iret = pthread_create( &t3, NULL, consume, NULL);
if(t3_iret)
{
fprintf(stderr,"Error - pthread_create() return code: %dn",t3_iret);
exit(EXIT_FAILURE);
}
pthread_join( t1, NULL);
pthread_join( t2, NULL);
pthread_join( t3, NULL);
return 0; }
另外,我想知道是否有可能用字符串而不是整数来做我所描述的事情。
edit1:当我尝试使队列成为字符串队列时,我得到::
/usr/local/include/boost/lockfree/queue.hpp: class boost::l lockfree::queue>实例化:/home/ubuntu/Project/src/main.cpp:15:37:此处需要/usr/local/include/boost/lockfree/queue.hpp:87:5: error: static assertion failed:(boost::has_trivial_destructor::value)BOOstrongTATIC_ASSERT (boost:: has_trivial_destructor:值));^/usr/local/include/boost/lockfree/queue.hpp:91:5: error: static assertion failed:(boost::has_trivial_assign::value)BOOstrongTATIC_ASSERT (boost:: has_trivial_assign:值));^在文件中包含/usr/local/include/boost/lockfree/queue.hpp:21:0从/home/ubuntu/Project/src/main.cpp: 5:/usr/local/include/boost/lockfree/detail/copy_payload.hpp:在' static void boost::lockfree::detail::copy_constructible_and_copyable::copy(T&, U &) [with T = std::basic_string;U = int ';/usr/local/include/boost/lockfree/detail/copy_payload.hpp:49:25: required from ' void boost::lockfree::detail::copy_payload(T&, U&) [with T = std::basic_string;U = int] '/usr/local/include/boost/lockfree/queue.hpp:402:61: required from ' bool boost::lockfree::queue::pop(U&) [with U = int;T = std:: base_string;A0 = boost::parameter::void_;A1 = boost::parameter::void;A2 = boost::参数参数::void_] '/home/ubuntu/Project/src/main.cpp:21:24:此处需要/usr/local/include/boost/lockfree/detail/copy_payload.hpp:38:11:错误:从' std::basic_string '类型转换为' int '类型无效
您需要在global.h
中声明而不是定义变量:
extern boost::lockfree::queue<int> q;
extern std::atomic<int> sum;
然后你需要在一个单独的文件global.cpp
:
boost::lockfree::queue<int> q{100};
std::atomic<int> sum{0};
我认为这应该解决你的问题。具体请参见如何使用extern在源文件之间共享变量?
至于第二部分,问为什么你不能做一个无锁队列的字符串,好吧,这是由错误消息回答:has_trivial_destructor
是假的std::string
,因为它是一个动态大小的字符串分配内存。您将无法在这种无锁队列中使用它。您可以尝试使用固定大小的字符串类,或者std::array<char, N>
。