int main()
{
	std::vector<thread> threads;
	glm::vec4 vectors[50000] = {};
	int chunkLength = 50000 / 10;

	ThreadingApp* app = new ThreadingApp();

	threads.push_back(thread(Alt, app));

	for (int i = 0; i < 10; i++)
	{
		threads.push_back(thread([&](int low, int high)
		{
			for (int j = low; j < high; j++)
			{
				vectors[j] = glm::normalize(vectors[j]);
				//std::cout << "Hello Thread " << j << " " << vectors[j].x << " " << vectors[j].y << " " << vectors[j].z << " " << vectors[j].w << std::endl;
			}
		}, i * chunkLength, (i + 1) * chunkLength
		));
	}

	for (auto& thread : threads)
		thread.join();

	return 0;
}
//  This test simulates some calls, and verifies that the waiting happens by
//  triggering what otherwise would be race conditions, and trying to detect
//  whether any of the race conditions happened.
TEST(EventBaseTest, RunInEventBaseThreadAndWait) {
  const size_t c = 256;
  vector<unique_ptr<atomic<size_t>>> atoms(c);
  for (size_t i = 0; i < c; ++i) {
    auto& atom = atoms.at(i);
    atom = make_unique<atomic<size_t>>(0);
  }
  vector<thread> threads(c);
  for (size_t i = 0; i < c; ++i) {
    auto& atom = *atoms.at(i);
    auto& th = threads.at(i);
    th = thread([&atom] {
        EventBase eb;
        auto ebth = thread([&]{ eb.loopForever(); });
        eb.waitUntilRunning();
        eb.runInEventBaseThreadAndWait([&] {
          size_t x = 0;
          atom.compare_exchange_weak(
              x, 1, std::memory_order_release, std::memory_order_relaxed);
        });
        size_t x = 0;
        atom.compare_exchange_weak(
            x, 2, std::memory_order_release, std::memory_order_relaxed);
        eb.terminateLoopSoon();
        ebth.join();
    });
  }
  for (size_t i = 0; i < c; ++i) {
    auto& th = threads.at(i);
    th.join();
  }
  size_t sum = 0;
  for (auto& atom : atoms) sum += *atom;
  EXPECT_EQ(c, sum);
}
Example #3
0
Player::Player(const string &file_name) :
		container_(new Container(file_name)),
		display_(new Display(container_->get_width(), container_->get_height())),
		timer_(new Timer),
		packet_queue_(new PacketQueue(queue_size_)),
		frame_queue_(new FrameQueue(queue_size_)) {
	stages_.push_back(thread(&Player::demultiplex, this));
	stages_.push_back(thread(&Player::decode_video, this));

	video();

}
void KDTree::minSAHCost(const Spheres& spheres, const BoundingBox& bbox, Axis axis, SAHCost& sahCost) const
{
	thread t;
	for(auto i = 0; i < spheres.count; ++i)
	{
		float leftPlane = spheres.centerCoords[axis][i] - spheres.radiuses[i];
		float rightPlane = spheres.centerCoords[axis][i] + spheres.radiuses[i];
		if(!bbox.inBoundingBox(leftPlane, axis))
		{
			continue;
		}

		BoundingBox left, right;
		bbox.split(axis, leftPlane, left, right);

		unsigned spheresLeft = 0, spheresRight = 0;
		t = thread(&KDTree::spheresCount, this, spheres, axis, bbox.vmin[axis],
				leftPlane, std::ref(spheresLeft));
		spheresCount(spheres, axis, leftPlane, bbox.vmax[axis], spheresRight);
		t.join();

		float sah = surfaceAreaHeuristic(bbox, axis, leftPlane, spheresLeft, spheresRight);
		if(sah < sahCost.cost)
		{
			sahCost.cost = sah;
			sahCost.splitAxis = axis;
			sahCost.splitPos = leftPlane;
		}

		if(!bbox.inBoundingBox(rightPlane, axis))
		{
			continue;
		}

		bbox.split(axis, rightPlane, left, right);
		t = thread(&KDTree::spheresCount, this, spheres, axis, bbox.vmin[axis],
				rightPlane, std::ref(spheresLeft));
		spheresCount(spheres, axis, rightPlane, bbox.vmax[axis], spheresRight);
		t.join();

		sah = surfaceAreaHeuristic(bbox, axis, rightPlane, spheresLeft, spheresRight);
		if(sah < sahCost.cost)
		{
			sahCost.cost = sah;
			sahCost.splitAxis = axis;
			sahCost.splitPos = rightPlane;
		}
	}
}
Example #5
0
	void run()
	{
		vector<thread> threads;

		for(auto f : tests_)
		{
			threads.emplace_back(
				thread(
					[f, this]()
					{
						while(!running_)
							std::this_thread::yield();

						f();
					}
			));
		}

		running_ = true;

		for(auto& t : threads)
			t.join();

		reset();
		

	}
Example #6
0
unsigned long bitCount_mt(const unsigned char byte[], size_t size,
			  int nthreads, function<int(unsigned char)> f) {
	size_t psize= size / nthreads;
	BitCounter **workers = new BitCounter*[nthreads];
	packaged_task<unsigned long> **tasks = new packaged_task<unsigned long>*[nthreads];
	unique_future<unsigned long> **futures = new unique_future<unsigned long>*[nthreads];
	for (int i= 0; i < nthreads; ++i) {
		const size_t nbytes= (i < nthreads-1)
					? psize
					: (size - (nthreads-1)*psize);
		workers[i]= new BitCounter(&byte[i*psize], nbytes, f);
		tasks[i]= new packaged_task<unsigned long>(*workers[i]);
		futures[i]= new unique_future<unsigned long>(tasks[i]->get_future());
		thread(move(*tasks[i]));
	}
	unsigned long count= 0;
	for (int i= 0; i < nthreads; ++i) {
		count += futures[i]->get();
		delete futures[i];
		delete tasks[i];
		delete workers[i];
	}
	delete[] futures;
	delete[] tasks;
	delete[] workers;
	return count;
}
Example #7
0
File: main.cpp Project: CCJY/coliru
int main()
{
	// Get the amount of "processing units"
	int n = std::thread::hardware_concurrency();
	
	// Create array of threads
	vector<ThreadItem> threadlist;
	threadlist.resize(n);
	
	// Spawn a thread for each core
	for(int i = 0;i < n;i++)
	{  threadlist[i].worker = thread(ThreadFunction,&threadlist[i].result); // pass rand() as data argument
	}
	
	// Wait for them all to finish
	for(int i = 0;i < n;i++)
	{  threadlist[i].worker.join();
	}
	
	// Present their calculation results
	printf("Results:\n");
	for(int i = 0;i < n;i++)
	{  printf("%s\n",threadlist[i].result);
	}
	
	// return EXIT_SUCCESS;  // return 0;
	// return EXIT_FAILURE;  // return 1;
	return EXIT_SUCCESS;
}
Example #8
0
int main(int argc, char* argv[]) {
    string iface;
    if (argc == 2) {
        // Use the provided interface
        iface = argv[1];
    }
    else {
        // Use the default interface
        iface = NetworkInterface::default_interface().name();
    }
    try {
        SnifferConfiguration config;
        config.set_promisc_mode(true);
        config.set_filter("udp and port 53");
        Sniffer sniffer(iface, config);
        dns_monitor monitor;
        thread thread(
            [&]() {
                monitor.run(sniffer);
            }
        );
        while (true) {
            auto info = monitor.stats().get_information();
            cout << "\rAverage " << info.average.count() 
                << "ms. Worst: " << info.worst.count() << "ms. Count: "
                << info.count << "   ";
            cout.flush();
            sleep_for(seconds(1));
        }
    }
    catch (exception& ex) {
        cout << "[-] Error: " << ex.what() << endl;
    }
}
Example #9
0
void Engine::GetTags(ostream& T, const vector<unsigned int>& l)
{
    vector<thread> threads;
    vector<stringstream> Ts;

    if (phase != endOfMessage)
        throw Exception("The phase must be endOfMessage to call Engine::GetTags().");
    Spark(true, l);

    for(unsigned int i=0; i<Pi; i++)
    {
        // Pistons[i].GetTag(T, l[i]);
        stringstream stream;
        Ts.push_back(stream);
        threads.push_back(thread(&Piston::GetTag, &Pistons[i], Ts.at(i), l[i]));
    }

    for(unsigned int i=0; i<Pi; i++)
    {
        threads.at(i).join();
        T.put(Ts.at(i).str());
    }

    phase = fresh;
}
Example #10
0
void Engine::Crypt(istream& I, ostream& O, bool unwrapFlag)
{
    vector<thread> threads;
    vector<ostream&> Os;

    if (phase != fresh)
        throw Exception("The phase must be fresh to call Engine::Crypt().");
    for(unsigned int i=0; i<Pi; i++)
    {
        // Pistons[i].Crypt(I, O, Et[i], unwrapFlag);
        stringstream stream;
        Os.push_back(stream);
        threads.push_back(thread(&Piston::Crypt, &Pistons[i], I, Os.at[i], Et[i], unwrapFlag));
    }

    for(unsigned int i=0; i<Pi; i++)
    {
        threads.at(i).join();
        O.put(Os.at(i).str());
    }

    if (hasMore(I))
        phase = crypted;
    else
        phase = endOfCrypt;
}
Example #11
0
// pathtrace an image with multithreading if necessary
image3f pathtrace(Scene* scene, bool multithread) {
    // allocate an image of the proper size
    auto image = image3f(scene->image_width, scene->image_height);

    // create a random number generator for each pixel
    auto rngs = RngImage(scene->image_width, scene->image_height);

    // if multitreaded
    if(multithread) {
        // get pointers
        auto image_ptr = &image;
        auto rngs_ptr = &rngs;
        // allocate threads and pathtrace in blocks
        auto threads = vector<thread>();
        auto nthreads = thread::hardware_concurrency();
        for(auto tid : range(nthreads)) threads.push_back(thread([=](){
            return pathtrace(scene,image_ptr,rngs_ptr,tid,nthreads,tid==0);}));
        for(auto& thread : threads) thread.join();
    } else {
        // pathtrace all rows
        pathtrace(scene, &image, &rngs, 0, 1, true);
    }

    // done
    return image;
}
Example #12
0
int main() {
	for (int i = 1; i <= 10; i++) q.enq(i);

	thread t[10];
	for (int i = 0; i < 3; i++) t[i] = thread(f);
	for (int i = 0; i < 3; i++) t[i].join();
}
/**
 *  Main routine... it's a bit ugly to hide main() inside this function, but
 *  it means we could easily switch to a different data structure by
 *  replacing ListBench.cpp, and main() wouldn't change at all.
 */
int main(int argc, char** argv)
{
    // parse the command line
    parseargs(argc, argv);

    // initialize the benchmark
    bench_init();

    // for tracking our threads
    std::thread threads[256];

    // launch the threads
    for (uint32_t j = 1; j < Config::CFG.threads; j++)
        threads[j] = thread(run, j);

    // all of the other threads should be waiting to run the benchmark, but
    // they can't until this thread starts the benchmark too...
    run(0);

    // everyone should be done.  Join all threads so we don't leave anything
    // hanging around
    for (uint32_t k = 1; k < Config::CFG.threads; k++)
        threads[k].join();

    // make sure the hash table is in a valid state
    bool v = bench_verify();
    std::cout << "Verification: " << (v ? "Passed" : "Failed") << "\n";

    // dump the results
    dump_csv();
}
Example #14
0
void test_queue() {
    SyncQueue<int> q;
    const int nthreads = 10;
    const int64_t qsize = 100;
    vector<thread> threads;
    for (int i = 1 ; i < qsize + 1; ++i) {
        q.push(i);
    }

    vector<int> qnt(nthreads);
    for(int i = 0; i < nthreads; ++i) {
        qnt[i] = 0;
        int limit = qsize / nthreads;
        threads.push_back(thread(test_queue_thread<int>, &q, &(qnt[i]), limit));
    }
    
    for(auto & x : threads) {
        x.join();
    }
    
    int64_t sum = 0;
    for(int i = 0; i < nthreads; ++i) {
        sum += qnt[i];
    }

    assert(sum == ((qsize * (qsize+1)) / 2));
    cout << "queue works" << endl;
}
Example #15
0
	void start()
	{
		should_stop_ = false;

		thread_ = std::move(
			thread([&]()
		{
			tio::Connection connection(host_name_);
			vector<tio::containers::list<string>> containers(container_names_.size());

			size_t count = container_names_.size();
			for(size_t i = 0; i < count; i++)
			{
				containers[i].create(
					&connection,
					container_names_[i].first,
					container_names_[i].second);

				containers[i].subscribe(std::bind([](){}));
			}

			while(!should_stop_)
			{
				connection.WaitForNextEventAndDispatch(1);
			}

			connection.Disconnect();

		}));
	}
Example #16
0
int main()
{
	ResetArrays();
	PrintWelcome();

	thread DEBUG_thread = thread(PrintDebugInfo);
	thread SKINCHANGER_thread = thread(SkinChanger);
	thread SETSKIN_thread = thread(SetSkinData);

	DEBUG_thread.join();
	SKINCHANGER_thread.join();
	SETSKIN_thread.join();

	delete Mem;
	return 0;
}
Example #17
0
int main(int argc, char *argv[]) {
    int sock, listener;
    struct sockaddr_in servaddr;
    char buf[1024];
    int bytes_read;
    string folder;

    cout << "starting server initialization" << endl;

    listener = socket(AF_INET, SOCK_STREAM, 0);
    if(listener < 0)
    {
        cout << "socket";
        return(0);
    }
    
    servaddr.sin_family = AF_INET;
    if (argc < 2) {
        servaddr.sin_port = htons(3425);
        cout << "server attached to port 3425" << endl;
    } else {
        servaddr.sin_port = htons(atoi(argv[1]));
        cout << "server attached to port " << argv[1] << endl;
    }
    if (argc < 3) {
       folder = "pages";
    }
    else {
        folder = argv[2];
    }
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(listener, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
    {
        cout << "bind" << endl;
        return(0);
    }

    listen(listener, 8);

    cout << "server initialized on socket " << listener << endl;

    uint quantity_of_kernel = std::thread::hardware_concurrency();

    if (argc >= 4){
        quantity_of_kernel = atoi(argv[4]);
    }

    vector <thread> array;
    for (uint i = 0; i < quantity_of_kernel; i++){
        array.push_back(thread([&folder, &listener, i](){thread_function(folder, listener, i);}));
    }

    for (uint i = 0; i < quantity_of_kernel; i++){
        array[i].join();
    }

    return 0;
}
Example #18
0
void Game::threading_ai(int threading, vector<int> &final_vector) {
   thread core = thread(std::bind (&Game::get_ai, this, 500, final_vector)); 
   vector<int> main_thread_weight(121,0);
   get_ai(500, main_thread_weight);
   core.join();

   final_vector = final_vector + main_thread_weight;


}
Example #19
0
void groupThreads(function<void(unsigned int)> tfn,
                  unsigned int numLow, unsigned int numHigh, unsigned int numPar) {
  const auto rl = ReportingLevel::Silent;
  using std::thread;
  const unsigned int threadsPerHWC = 4;
  unsigned int numHWC = 0;
  const unsigned int dfltNumThreads = 10;
  if (0 == numPar) { // no specific number requested, so guess

    // As of OCt. 2016, this function might or might not have one or two
    // of the following problems, depending on your implementation.
    // 1: It might not be implemented, and just return 0.
    // 2: It might not take into account "hyperthreading", and return
    //    half the expected number.
    numHWC = std::thread::hardware_concurrency();
    if (0 == numHWC) {
      numPar = dfltNumThreads; // arbitrary default
    }
    else {
      // four times the number of threads is not too inefficient,
      // and 2 times the number of hyperthreads is not too wasteful.
      numPar = threadsPerHWC * numHWC;
    }
  }
  if (ReportingLevel::Silent < rl) {
    if (0 == numHWC) {
      LOG(INFO) << "Could not detect hardware concurrency";
    }
    else {
      LOG(INFO) << "Detected hardware concurrency:" << numHWC;
    }
    LOG(INFO) << "Using groups of" << numPar;
  }

  unsigned int cntr = numLow;
  while (cntr <= numHigh) {
    vector<thread> myThreads = {};
    for (unsigned int i = 0; ((i < numPar) && (cntr <= numHigh)); i++) {
      if (ReportingLevel::Medium < rl) {
        LOG(INFO) << KBase::getFormattedString(
          "Launching thread %3u / %3u / [%3u,%3u]", i, cntr, numLow, numHigh);
      }
      myThreads.push_back(thread(tfn, cntr));
      cntr++;
    }
    if (ReportingLevel::Low < rl) {
      LOG(INFO) << "Joining ...";
    }
    for (auto& ti : myThreads) {
      ti.join();
    }
  }
  return;
}
Example #20
0
DLL_PUBLIC lbool SATSolver::solve(const vector< Lit >* assumptions)
{
    //Reset the interrupt signal if it was set
    data->must_interrupt->store(false, std::memory_order_relaxed);

    if (data->log) {
        (*data->log) << "c Solver::solve( ";
        if (assumptions) {
            (*data->log) << *assumptions;
        }
        (*data->log) << " )" << endl;
    }

    if (data->solvers.size() > 1 && data->sql > 0) {
        std::cerr
        << "Multithreaded solving and SQL cannot be specified at the same time"
        << endl;
        exit(-1);
    }

    if (data->solvers.size() == 1) {
        data->solvers[0]->new_vars(data->vars_to_add);
        data->vars_to_add = 0;

        lbool ret = data->solvers[0]->solve_with_assumptions(assumptions);
        data->okay = data->solvers[0]->okay();
        return ret;
    }

    //Multi-thread from now on.
    DataForThread data_for_thread(data, assumptions);
    std::vector<std::thread> thds;
    for(size_t i = 0
        ; i < data->solvers.size()
        ; i++
    ) {
        thds.push_back(thread(OneThreadSolve(data_for_thread, i)));
    }
    for(std::thread& thread : thds){
        thread.join();
    }
    lbool real_ret = *data_for_thread.ret;

    //This does it for all of them, there is only one must-interrupt
    data_for_thread.solvers[0]->unset_must_interrupt_asap();

    //clear what has been added
    data->cls_lits.clear();
    data->vars_to_add = 0;
    data->okay = data->solvers[*data_for_thread.which_solved]->okay();
    return real_ret;
}
Example #21
0
void GradArgs::sum_explx0_grad(ftype *buf, const int64_t s, const int64_t e) {
  const int64_t SUM_SIZE = (e - s) + (3*K);
  const int64_t STEP_SIZE = SUM_SIZE / NUM_THREADS / 2;

  for (int i = 0; i < 2; i++) {
    vector<thread> t(NUM_THREADS);
    for (size_t j = 0; j < t.size(); j++) {
      int64_t s_offset = -K + STEP_SIZE * (2*j + i);
      int64_t e_offset = -K + STEP_SIZE * (2*j + i + 1);
      t[j] = thread(&GradArgs::sum_explx0_grad_worker, this, buf + s_offset,
                    s + s_offset, s + e_offset);
    }
    for (size_t j = 0; j < t.size(); j++)
      t[j].join();
  }
}
Example #22
0
int main()
{
	try
	{
		string host;
		cout << "Enter the host: ";
		cin >> host;
		if( host == "l" )
			host = "localhost";

		string port;
		cout << "Enter the port: ";
		cin >> port;

		string username;
		cout << "Enter your username: "******"Enter your password: "******"Exception: " << e.what() << "\n";
	}

	system( "pause" );
	return 0;
}
Example #23
0
int main5a() {
	shared_ptr<boost::asio::io_service> io_service(new boost::asio::io_service);
	shared_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(*io_service));

	cout << "[" << std::this_thread::get_id()
		<< "] The program will exit when all work has finished." << endl;

	vector<thread> threads;
	for (auto i = 0; i < 2; ++i)
		threads.push_back(thread(WorkerThread5a, io_service));

	io_service->post(bind(RaiseAnException, io_service));

	for (auto& th : threads) th.join();

	return 0;
}
Example #24
0
int main()
{
    debuglog("start...\n");
    initRandSeed();

    //SCGIApp cgi;
    cgi.set(Default);
    cgi.set(Home);
    cgi.set(Guestbook);
    cgi.set(Photo);
    cgi.set(UPage);
    cgi.set(Search);
    cgi.set(Profile);
    cgi.set(Rating);
    cgi.set(Chatroom);
    cgi.set(Login);
    cgi.set(News);
    cgi.set(Feedback);
    cgi.set(Verify);
    cgi.set(TestBrowser);
    cgi.set(Others);

    if (!sql.connect(dbserver, dbuser, dbpwd, dbname, 3306))
    {
        errorlog("MySQL connect faild: %s\n", sql.error());
        return -1;
    }

    if (!selfCheck())
        return -1;

    debuglog("fcgi init...\n");
    int n = FCGX_Init();
    if (n != 0)
    {
        errorlog("fcgi init failed(%d)\n", n);
        return -1;
    }
    for (int i = 1; i < THREAD_COUNT; ++i)
        thread(doit).detach();
    doit();

    onExit();
    return 0;
}
Example #25
0
int main()
{
    vector<thread> hilos;

    for(int g{} ; g < 10; ++g)		//creando 10 hilos
    {
        hilos.push_back(thread(vehiculo, g));
    }
    
    for(auto &i : hilos)		//uniendo los 10 hilos a main()
    {
        i.join();
    }

    cout << endl;

    return 0;
}
Example #26
0
static bool actually_add_clauses_to_threads(CMSatPrivateData* data)
{
    DataForThread data_for_thread(data);
    std::vector<std::thread> thds;
    for(size_t i = 0; i < data->solvers.size(); i++) {
        thds.push_back(thread(OneThreadAddCls(data_for_thread, i)));
    }
    for(std::thread& thread : thds){
        thread.join();
    }
    bool ret = (*data_for_thread.ret == l_True);

    //clear what has been added
    data->cls_lits.clear();
    data->vars_to_add = 0;

    return ret;
}
Example #27
0
int main()
{
	cout <<"Trabajando en el hilo principal" << endl;

	const size_t max{ 10 };
	vector<thread> hilos;

	for(int i{ 0 }; i < max; ++i)
	{
		hilos.push_back(thread(funcionHilo, i));
	}

	cout << endl <<"Ya inicialize " << max <<" hilos desde main" << endl;

	for(int i{ 0 }; i < hilos.size(); ++i)
	{
		hilos.at(i).join();
	}

	return 0;
}
Example #28
0
int main6b() {
    shared_ptr<boost::asio::io_service> io_service(new boost::asio::io_service);
    shared_ptr<boost::asio::io_service::work> work(new boost::asio::io_service::work(*io_service));

    cout << "[" << std::this_thread::get_id() << "] Press [return] to exit." << endl;

    vector<thread> threads;
    for (auto i = 0; i < 2; ++i)
        threads.push_back(thread(WorkerThread6b, io_service));

    shared_ptr<boost::asio::deadline_timer> timer( new boost::asio::deadline_timer(*io_service));
    timer->expires_from_now(boost::posix_time::seconds(1));
    timer->async_wait(bind(TimerHandler6b, _1, timer));

    cin.get();

    io_service->stop();

    for (auto& th : threads) th.join();

    return 0;
}
Example #29
0
void PacketCapturer::start_capture() {
    using std::placeholders::_1;

    mutex mtx;
    condition_variable cond;
    bool started = false;

    running_ = true;
    sniffer_thread_ = thread([&]() {
        {
            lock_guard<mutex> _(mtx);
            started = true;
            cond.notify_one();
        }
        sniffer_->sniff_loop(bind(&PacketCapturer::callback, this, _1));
    });

    unique_lock<mutex> locker(mtx);
    while (!started) {
        cond.wait(locker);
    }
}
Example #30
0
void check(int limit , int64_t nthreads) {
    M mutex;
    int value = 1;
    vector<int> thrcount(nthreads , 0);
    vector<thread> threads;
    for(int i = 0 ;  i < nthreads ;++ i) {
        threads.push_back(thread(inc<M>, &mutex , &value , &limit , &thrcount[i]));
    }

    for(auto & x : threads) {
        x.join();
    }
    int64_t sum = 0;
    for(int i = 0; i < nthreads; ++i) {
        sum += thrcount[i];
    }
    
    int exp = 1;
    
    for(int i = 0; i < nthreads * QNT; ++i) change(&exp);
    assert(value == exp);
//    assert(value == sum && value == limit);
}