简体   繁体   English

如何在没有同步的情况下使用多个线程(2、4、8、16 个线程)在循环(10,100、1000 个循环)中打印字符串?

[英]How can I print a string in a loop (10,100, 1000 cycles) using multiple threads (2, 4,8 , 16 threads) with no synchronization?

I need to write a program that will print characters onto console.我需要编写一个将字符打印到控制台的程序。 The threads need not be synchronized, which means that the data will be mixed and the output should be messy.线程不需要同步,这意味着数据会混合,output 应该是杂乱无章的。 However, my output works fine and it seems like I'm doing something wrong.但是,我的 output 工作正常,似乎我做错了什么。

typedef struct {
    std::string info;
    unsigned int m_number;
    unsigned m_cycles;
    unsigned m_currentThread;
}data;

unsigned int __stdcall Func(void* d) {
    data* real = (data*)d;
    std::cout << "Current thread ID: " << GetCurrentThreadId() << std::endl;
    int i = 0;
    for (int j = (real->m_currentThread - 1) * real->m_cycles / real->m_number;j < real->m_currentThread * real->m_cycles / real->m_number;j++) {
        std::cout << real->info << std::endl;
        }

    return 0;
}

int main(int argc, char* argv[]) {
    int threadsNumber;
    std::string str;
    std::getline(std::cin, str);
    std::cout << "Enter the number of threads:\n";
    std::cin >> threadsNumber;
    int cycles;
    std::cout << "Enter the number of cycles:\n";
    std::cin >> cycles;
    std::vector<HANDLE> threads;
    HANDLE tmp;
    data* args = new data;
    args->info = str;
    args->m_number = threadsNumber;
    args->m_cycles = cycles;
    for (int i = 1;i <= threadsNumber;++i) {
        args->m_currentThread = i;
        tmp = (HANDLE)_beginthreadex(0, 0, &Func, args, 0, 0);
        Sleep(1000L);
        threads.push_back(tmp);
    }
    WaitForMultipleObjects(threads.size(), &threads.front(), TRUE, INFINITE);

    getchar();
    return 0;
}

The output should be character-wise and the strings should get messy, since there's no synchronization between the threads yet. output 应该是字符方面的,并且字符串应该变得混乱,因为线程之间还没有同步。

The output should be character-wise and the strings should get messy output 应该是字符方面的,字符串应该变得混乱

This is not backed by the contract of std::cout :这不受std::cout合同的支持:

Unless sync_with_stdio(false) has been issued, it is safe to concurrently access these objects from multiple threads for both formatted and unformatted output.除非已发出sync_with_stdio(false) ,否则对于格式化和未格式化 output 从多个线程同时访问这些对象是安全的。

The observed behavior matches the expected behavior.观察到的行为与预期的行为相匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM