mardi 3 février 2015

C++ 11 thread and pointer parameter

I want to print strings with contents 1,2,3,4,5 using 5 threads, My working environment:


OS version : CentOS Linux release 7.0.1406 (Core)


g++ version: g++ (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16)


compile cmd: g++ -o thread_sz -std=c++11 -pthread thread_sz.cpp



// file name: thread_sz.cpp
#include <iostream>
#include <string>
#include <thread>

#include <unistd.h>

using namespace std;

void myFunc1(char* sz)
{
printf("sz = %s\n", sz);
}

void myFunc2(const char* const sz)
{
printf("const char* const sz = %s\n", sz);
}

void myFunc3(string str)
{
printf("string str = %s\n", str.c_str());
}

int main(int argc, char* argv[])
{
for(int i = 1; i <= 5; i++) {
char sz[16];
sprintf(sz, "%2d", i);
const string str(sz);

std::thread t1(myFunc1, sz);
std::thread t2(myFunc2, (const char* const)str.c_str());
std::thread t3(myFunc3, str);

t1.detach();
t2.detach();
t3.detach();
}
usleep(1000000); // sleep 1 second
return 0;
}


Output something like:



const char* const sz = 1
sz = 3
const char* const sz = 2
string str = 3
sz = 4
sz = 4
string str = 2
sz = 5
const char* const sz = 4
sz = 5
string str = 1
const char* const sz = 5
string str = 4
string str = 5
const char* const sz = 5


I run the program for lots of times, and the result seems:



string str output: 100% correct
sz output: ~10% correct
const char* const sz output: ~50% correct


My questions are:


1, Why MyFunc1 and MyFunc2 are not 100% correct, what's the differences btw them. How to fix it.


2, Can MyFunc3 work 100% correctly.


3, If I comment out this line usleep(1000000); // sleep 1 second MyFunc1 may output empty value like sz =, Why?


Thank you very much.


Aucun commentaire:

Enregistrer un commentaire