简体   繁体   中英

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. However, my output works fine and it seems like I'm doing something wrong.

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.

The output should be character-wise and the strings should get messy

This is not backed by the contract of 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.

The observed behavior matches the expected behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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