其他分享
首页 > 其他分享> > c – 在C中使用英特尔TBB

c – 在C中使用英特尔TBB

作者:互联网

我正在尝试在C中使用英特尔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.

标签:c-3,c,intel,tbb
来源: https://codeday.me/bug/20190831/1772786.html