我正在尝试在C语言中使用Intel TBB。我为TBB获得的所有文档都针对C ++。TBB是否可以与普通C一起使用?如果是,我如何定义原子整数。在下面的代码中,我尝试使用模板atomic<int> counter
(我知道这在C语言中不起作用)。有没有办法解决这个问题?
#include<pthread.h>
#include<stdio.h>
#include<tbb/atomic.h>
#define NUM_OF_THREADS 16
atomic<int> counter;
void *simpleCounter(void *threadId)
{
int i;
for(i=0;i<256;i++)
{
counter.fetch_and_add(1);
}
printf("T%ld \t Counter %d\n", (long) threadId, counter);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
counter=0;
pthread_t threadArray[NUM_OF_THREADS];
long i;
for(i=0;i<NUM_OF_THREADS;i++)
{
pthread_create(&threadArray[i], NULL, simpleCounter, (void *)i);
}
pthread_exit(NULL);
}
-bash-4.1$ g++ simpleCounter.c -I$TBB_INCLUDE -Wl,-rpath,$TBB_LIBRARY_RELEASE -L$TBB_LIBRARY_RELEASE -ltbb
simpleCounter.c:7: error: expected constructor, destructor, or type conversion before ‘<’ token
simpleCounter.c: In function ‘void* simpleCounter(void*)’:
simpleCounter.c:16: error: ‘counter’ was not declared in this scope
simpleCounter.c:18: error: ‘counter’ was not declared in this scope
simpleCounter.c: In function ‘int main(int, char**)’:
simpleCounter.c:24: error: ‘counter’ was not declared in this scope
hivert是正确的,C和C ++是不同的语言。
尝试这个:
#include<pthread.h>
#include<stdio.h>
#include<tbb/atomic.h>
#define NUM_OF_THREADS 16
tbb::atomic<int> counter;
void *simpleCounter(void *threadId)
{
int i;
for(i=0;i<256;i++)
{
counter.fetch_and_add(1);
}
printf("T%ld \t Counter %d\n", (long) threadId, (int)counter);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
counter=0;
pthread_t threadArray[NUM_OF_THREADS];
long i;
for(i=0;i<NUM_OF_THREADS;i++)
{
pthread_create(&threadArray[i], NULL, simpleCounter, (void *)i);
}
for(i=0;i<NUM_OF_THREADS;i++)
pthread_join(threadArray[i], nullptr);
}
用.cpp扩展名保存(g ++不需要)。我修改了缺少的名称空间tbb :: atomic,最后还加入了一个连接,以等待所有线程完成后再退出main。它应该现在编译。将-std = c ++ 11添加为编译器选项,或将nullptr更改为NULL。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句