Actually this discussion went in the totally wrong direction, mostly because it wasn't stated early enough that VS 2008 was being used. Being as POSIX compliant as they are MS went and made all the thread-unsafe functions in the C runtime thread-safe in their runtime libraries, which is also the reason they don't need to have rand_r.
In the MS runtime the rand() state is stored locally per thread, which means you can use rand() without mutexes, you just have to make sure to seed each thread with a different value (this means you shouldn't use time()).
#include <ctime>
#include <iostream>
#include <vector>
#include <SFML/System.hpp>
class Myc
{
public:
Myc()
{
if(!seed)
{
seed = time(NULL);
}
}
~Myc()
{
for (int i = 0; i < m_threads.size(); ++i)
if(sf::Thread* thr = m_threads[i])
{
thr->terminate();
delete thr;
}
m_threads.clear();
}
void Start()
{
// 3 thread
for (int i = 0; i < 3; ++i)
m_threads.push_back(new sf::Thread(&Myc::ThrFun, this));
for (int i = 0; i < m_threads.size(); ++i)
m_threads[i]->launch();
}
void ThrFun()
{
sf::Clock clock;
srand(seed++);
while (true)
{
if (clock.getElapsedTime().asSeconds() >= 3)
{
int r = rand()%100+1;
std::cout << r << std::endl;
clock.restart();
}
}
}
private:
static unsigned int seed;
std::vector<sf::Thread*> m_threads;
};
unsigned int Myc::seed = 0;
int main()
{
Myc m;
m.Start();
std::cin.get();
}
This should work, but only on Windows does it run safely.