Ubuntu 11.10 Vmware中的多线程

时间:2012-12-29 01:24:02

标签: pthreads

我正在使用“pthread”库在C ++中编写多线程程序,但是当我在Ubuntu虚拟机上执行它时,我的线程似乎没有并行运行,尽管我有一个多核处理器(i7-2630QM) )...代码太长所以我将用这个简单的代码来解释我的问题:

#include <iostream>
#include <pthread.h>
using namespace std;

void* myfunction(void* arg); //function that the thread will execute

int main()
{
    pthread_t thread;
    pthread_create(&thread, NULL, myfunction, NULL); //thread created
    for (int i=0; i<10; i++) //show "1" 10 times
         cout << "1";
    pthread_join(thread, NULL); //wait for the thread to finish executing
    return 0;
}

void* myfunction(void* arg)
{
    for (int j=0; j<10; j++) //show "2" 10 times
         cout << "2";
    return NULL;
}

当我在我的主机操作系统(带有VC ++ 2010的Windows 7)上运行此代码时,我得到的结果如12212121211121212...,这是多线程应用程序应该执行的操作,但是当我运行相同的代码时客户操作系统(Ubuntu on Vmware with Code :: Blocks)我总是得到11111111112222222222 !!! AFAIK线程应该与main()函数并行运行,而不是顺序运行。我的VM的核心编号设置为4,但似乎程序只使用一个核心,我不知道出了什么问题?这是代码还是......?我在这里错过了什么吗? 我感谢任何帮助,提前谢谢,请原谅我的英文:/

2 个答案:

答案 0 :(得分:0)

使用信号量(全局或作为参数传递给我的函数)来正确同步线程。由于操作系统之间的不同调度特性,您可能会遇到计时问题(这本身并不是一个问题)。在调用pthread_create之后让第一个线程在信号量上等待,并在输入myfunction后立即让新线程发出信号。

此外,你的循环很短,使它们需要更长的时间。

example here

答案 1 :(得分:0)

Windows和Linux CRT / STDC ++库具有不同的同步行为。通过调用cout,您无法了解有关并行执行的任何信息。写一些实际的并行计算并测量经过的时间来判断发生了什么。