Passing functions as parameters in order to simplify thread creation - c++

I'm trying to write a small piece of code that just makes using CreateThread() slightly more clean looking. I can't say that I'm really intending on using it, but I thought it would be a fun, small project for a newer programmer like myself. Here is what I have so far:
#include <iostream>
#include <windows.h>
using namespace std;
void _noarg_thread_create( void(*f)() )
{
cout << "Thread created...\n" << endl;
Sleep(10);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)f, NULL, 0, NULL);
}
template <typename T>
void _arg_thread_create( void(*f)(T), T* parameter)
{
cout << "Thread created...\n" << endl;
Sleep(10);
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)*f, parameter, 0, NULL);
}
void printnums(int x)
{
for(int i = x; i < 100; i++)
{
cout << i << endl;
}
}
void printnumsnoarg()
{
for(int i = 0; i < 100; i++)
{
cout << i << endl;
}
}
int main()
{
cin.get();
_noarg_thread_create( &printnumsnoarg );
cin.get();
int x = 14;
_arg_thread_create( &printnums, &x );
cin.get();
}
Basically I have two functions that will call two different presets for CreateThread: one for when a parameter is needed in the thread, and one for when no parameter is needed in the thread. I can compile this with the g++ compiler (cygwin), and it runs without any errors. The first thread gets created properly and it prints out the numbers 0-99 as expected. However, the second thread does not print out any numbers (with this code, it should print 14-99). My output looks like this:
<start of output>
$ ./a.exe
Thread created...
0
1
2
3
.
.
.
97
98
99
Thread Created...
<end of output>
Any ideas why the second thread isn't working right?

you actually seem to miss you're passing a pointer to your printnums(int x) function. As the storage location of x in your main function will be a lot bigger than 100 your loop never runs.
You should try to change printnums to:
void printnums(int *x)
{
for(int i = *x; i < 100; i++)
{
cout << i << endl;
}
}
I guess everything will work as expected then.

Related

how to count number of a specific function be called at compile time

A program is divided into N functions.
Like the following code snippets: after calling each function, I wanna show the progress count/N
how to count N at compile time ?
#include <iostream>
using namespace std;
double progress()
{
int const total = 4; // how to get 4?
static int counter = 0;
return static_cast<double>(counter++) / static_cast<double>(total);
}
int main()
{
cout << progress() << endl; // 0.25
cout << progress() << endl; // 0.5
cout << progress() << endl; // 0.75
cout << progress() << endl; // 1.0
return 0;
}
I tried constexpr function, but cannot increment a variable.
Imagine the following code:
int main() {
cout << "N = ";
int N;
cin >> N;
for (int i = 0; i < N; ++i) cout << 'progress()' << endl;
}
There is absolutely no way, the compiler can know how many times the function will be executed. So you need to determine the number using the logic of your data.
If you want to know how many times you call progress without loops, recursions, conditions etc., the only way I can think of is using external tool on the source file. E.g.
cat source.cpp | grep -o progress() | wc -l
Just remember to subtract 1 from the result, which accounts for the function definition.
You can't do it, but you could fake it by making the printing happen after N (function call count) is known.
static struct counter_impl {
int n = 0;
constexpr void operator ()() noexcept { ++n; }
friend std::ostream& operator<<(std::ostream& os, counter_impl const& self) {
os << std::fixed;
std::generate_n(std::ostream_iterator<double>(os, "\n"), self.n,
[i = 1, N = static_cast<double>(self.n)] () mutable { return i++ / N; });
return os << std::defaultfloat;
}
} counter;
int main() {
counter();
std::cout << counter; // 1.00
}
Live example on compiler explorer
Unfortunately, you cannot.
This is not something that can be determined at compile time.
See https://en.wikipedia.org/wiki/Halting_problem

threaded for loop reaching values it's not supposed to reach

I'm messing around with multithreading in c++ and here is my code:
#include <iostream>
#include <vector>
#include <string>
#include <thread>
void read(int i);
bool isThreadEnabled;
std::thread threads[100];
int main()
{
isThreadEnabled = true; // I change this to compare the threaded vs non threaded method
if (isThreadEnabled)
{
for (int i = 0;i < 100;i++) //this for loop is what I'm confused about
{
threads[i] = std::thread(read,i);
}
for (int i = 0; i < 100; i++)
{
threads[i].join();
}
}
else
{
for (int i = 0; i < 100; i++)
{
read(i);
}
}
}
void read(int i)
{
int w = 0;
while (true) // wasting cpu cycles to actually see the difference between the threaded and non threaded
{
++w;
if (w == 100000000) break;
}
std::cout << i << std::endl;
}
in the for loop that uses threads the console prints values in a random order ex(5,40,26...) which is expected and totally fine since threads don't run in the same order as they were initiated...
but what confuses me is that the values printed are sometimes more than the maximum value that int i can reach (which is 100), values like 8000,2032,274... are also printed to the console even though i will never reach that number, I don't understand why ?
This line:
std::cout << i << std::endl;
is actually equivalent to
std::cout << i;
std::cout << std::endl;
And thus while thread safe (meaning there's no undefined behaviour), the order of execution is undefined. Given two threads the following execution is possible:
T20: std::cout << 20
T32: std::cout << 32
T20: std::cout << std::endl
T32: std::cout << std::endl
which results in 2032 in console (glued numbers) and an empty line.
The simplest (not necessarily the best) fix for that is to wrap this line with a shared mutex:
{
std::lock_guard lg { mutex };
std::cout << i << std::endl;
}
(the brackets for a separate scope are not needed if the std::cout << i << std::endl; is the last line in the function)

simple for loop finishes and fails the run

For some unknown reason this simple code runs, does what it's expected to do and then crashes the run. I am using NetBeans IDE, which overlapped my arrays before (tends to be buggy), so I was wondering if someone gets the same error - that would mean I certainly have to change the IDE environment.
#include <iostream>
using namespace std;
int main ()
{
int first[4][4];
for (int a = 0; a < 5; a++)
{
for (int b = 0; b < 5;b++)
{
cout << a << " " << b << " ";
if (first [a][b] != 0)
{
first[a][b] = 0;
}
cout << first[a][b] << " ";
}
cout << endl << endl << endl;
}
return 0;
};
here you are declearing a array with 4 indexes.In c/c++ index number starts at 0.
In your code you are saying :
int first[4][4];
that means indexs are : 0 1 2 3.Array length or total index are 4.
But in for loop you are saying
for (int a = 0; a < 5; a++) {
....
}
so you are trying to access index number 0 1 2 3 4 respectively.But remember you don't have index number 4.That is why it should give array index out of bound error.
Also at the end of main function you are using a semicolon.remove that
main () {
....
};
Hope this solves the problem.From next time Please try to provide details about the errors your IDE is giving you as it will be easier for the people who are giving answer.

Boost::thread crashes during simple loop

I am trying out some simple boost::thread code, as follows:
#include <iostream>
#include <boost/thread.hpp>
void InputLoop()
{
std::cout << "Loop start" << std::endl;
int y = 0;
while (1)
{
std::cout << "y = " << y << std::endl;
y++;
}
std::cout << "Loop end" << std::endl;
}
int main()
{
std::cout << "Main start" << std::endl;
boost::thread t(InputLoop);
t.start_thread();
while (1)
{
int x = 0;
}
std::cout << "Main end" << std::endl;
return 0;
}
This gives the output:
Main start
Loop start
y = 0
y = 1
y = 2
.
.
.
The program has unexpectedly finished
So, it is crashing during InputLoop(). The value of y when the crash occurs varies between different runs, and ranges from about 0 to about 10000.
What's going on?
You shouldn't call start_thread?
This is not required, as it's a leaked internal implementation detail:
https://svn.boost.org/trac/boost/ticket/9632
In my code I accidentally called this method and it resulted in my callback being started twice.
So you get unsynchronized access to std::cout, y which leads to Undefined Behaviour
The fix is found in this commit: https://github.com/boostorg/thread/commit/750c849b0f0dff79a289111955260a4147ac7f59
Even though there is a public method start_thread in class thread, it isn't in the documentation. That's for a reason:
Launching threads
A new thread is launched by passing an object of a callable type that can be invoked with no parameters to the constructor. [...]
If you wish to construct an instance of boost::thread with a function or callable object that requires arguments to be supplied, this can be done by passing additional arguments to the boost::thread constructor:
Regardless which constructor you use, the thread is already running:
// <boost/thread/detail/thread.hpp>
template <
class F
>
explicit thread(BOOST_THREAD_RV_REF(F) f
//, typename disable_if<is_same<typename decay<F>::type, thread>, dummy* >::type=0
):
thread_info(make_thread_info(thread_detail::decay_copy(boost::forward<F>(f))))
{
start_thread();
}
How's start_thread defined?
void start_thread()
{
if (!start_thread_noexcept())
{
boost::throw_exception(thread_resource_error());
}
}
start_thread_noexcept is actually not in a header, but part of libboost_thread:
// boost/lib/thread/src/thread.cpp
bool thread::start_thread_noexcept()
{
thread_info->self=thread_info;
int const res = pthread_create(&thread_info->thread_handle, 0, &thread_proxy, thread_info.get());
if (res != 0)
{
thread_info->self.reset();
return false;
}
return true;
}
You actually created two threads. And it's (probably) the thread_proxy implementation that creates your behaviour.

Calling function in C++

I'm trying to call a function with no return type but it doesn't seem to be getting called.
The code looks something like this(summarized):
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int ItemsInQuestion[4];
void GetQuestions(int NumQuests);
int main()
{
int NumberOfQuestions = 0;
srand((unsigned)time(NULL));
cout << "How many questions would you like?" << endl;
cin >> NumberOfQuestions;
cout << NumberOfQuestions << " questions will be asked.";
GetQuestions(NumberOfQuestions);
system ("PAUSE");
return 0;
}
void GetQuestions(int NumQuests)
{
for(int Questions=NumQuests; Questions>NumQuests; Questions++)
{
ItemsInQuestion[0]=(rand()%(263))+1;
ItemsInQuestion[1]=(rand()%(263))+1;
ItemsInQuestion[2]=(rand()%(263))+1;
ItemsInQuestion[3]=(rand()%(263))+1;
cout << ItemsInQuestion[0] << ' ' << ItemsInQuestion[1] << ' ' <<ItemsInQuestion[2] << ' ' << ItemsInQuestion[3];
}
}
The line that outputs the values in the array never comes up. What is causing this?
Because
int Questions=NumQuests;
and
Questions>NumQuests;
don't like each other.
You set Questions to NumQuests and then tell the loop to keep going as long as Questions is strictly greater than NumQuests, which it isn't to start off with.
Even if it was, you'd soon run into an overflow and undefined behavior.
This is not the way of using for-loops :
for ( __Initialization, __Condition, __Increment)
As Grigore pointed out in his answer, your initialization is wrong. As Questions=NumQuest, the statement Questions>NumQuests is false from the beginning, and your code is equivalent to
for ( ; 1<1 ; ) // I'm a lazy loop, I'm ugly and useless
There is an infinite number of way to do what you want :
// Direct : 0, 1, 2, .. NumQuest-1.
for (int Questions=0 ; Questions < NumQuests ; Questions++)
{ ... }
// Reverse : NumQuest, ..., 2, 1.
for (int Questions=NumQuests ; Questions > 0 ; Questions--)
{ ... }