Can't pthreads access variables from the main() function? - c++

int main()
{
int i;
pthread_t t;
}
Can t not see i? t is created inside main, right? That means it must be using the same shared memory main() is using? How do I make it see i without making i a global variable?

pthreads aren't special. For instance, the following code has the same "problem":
void foo()
{
i = 5;
}
int main()
{
int i;
foo();
}
Surely foo is called by main, so they're even on the same thread. Yet foo doesn't see the int in main. The solution is simple: if foo needs an int, main should pass that:
void foo(int& i)
{
i = 5;
}
int main()
{
int i;
foo(i);
}
With threads, the situation is the same: pass what you need to share.

What? t is a thread, it doesn't really "see" anything. Strictly, it's a variable that represents a thread -- you haven't actually created a thread -- but assuming you do create one, it runs in the same process as main(), so it shares memory space in that sense, but it doesn't share the scope of main. The functions which run in that thread can see whatever variables are in scope for those functions.
You could pass a pointer to i as the user data pointer to pthread_create. Or if you need to access more than just i, you could pass a pointer to some structure which contains (among other things) a pointer to i, and so on.
Example code:
#include <pthread.h>
#include <iostream>
#include <cstring>
void *thread_entry_point(void *data) {
int *idata = static_cast<int*>(data);
std::cout << "thread: i = " << *idata << "\n";
*idata = 23;
return const_cast<char*>("might as well return something");
}
int main() {
int i = 12;
pthread_t thr;
int err = pthread_create(&thr, 0, thread_entry_point, &i);
if (err == 0) {
void *result;
pthread_join(thr, &result);
std::cout << "main: result = " << static_cast<const char*>(result) << "\n";
std::cout << "main: i = " << i << "\n";
} else {
std::cout << "error creating thread: " << err << " " << std::strerror(err) << "\n";
}
}

Related

Integer pointer only has correct value if I print it

I am implementing my own smart_pointer, which counts the references to the thing it points to. Here is my implementation so far:
#pragma once
#include <iostream>
template <typename T>
class smart_pointer{
T* pointer;
int* cnt;
public:
smart_pointer<T>(T *el): pointer(el) { int i = 1; cnt = &i; }; //
smart_pointer<T>(const smart_pointer<T>& other): pointer(other.pointer) {
// std::cout << ", *(other.cnt): " << *(other.cnt);
cnt = other.cnt;
(*cnt)++;
} // Copy-constructor
int counter(){
int c = *cnt;
return c;
}
};
In main.cpp, I did the following:
int main(){
// smart_pointer_examples();
std::string h("hello");
smart_pointer<std::string> p(&h);
std::cout << "p: " << p.counter();
smart_pointer<std::string> q(p);
std::cout << ", q: " << q.counter() << std::endl;
return 0;
}
The problem is that that outputs p: 1, q: 6487781. After a lot of time trying to find the issue by debugging and printing stuff, I found something that fixed my issue: By adding std::cout << ", *(other.cnt): " << *(other.cnt); somewhere in my copy-constructor, the output becomes p: 1, *(other.cnt): 1, q: 2, which is the desired behaviour. I can't for the life of me think of why printing the counter would change anything.
Edit: Also, if I only do *(other.cnt) without std::cout, the same problem that I started with happens.
You made a small mistake in implementing your idea.
I will not comment on the design of your smart pointer implementation.
The problem is that you implemented your counter as a pointer. That is wrong.
And, you are dereferencing a local variable. That is a semantic bug. The result is undefined. The value of the counter will be indeterminate. Additionally you should initialize your class members.
If we fix both, then your code will look like:
#pragma once
#include <iostream>
template <typename T>
class smart_pointer {
T* pointer{};
int cnt{};
public:
smart_pointer<T>(T* el) : pointer(el) { cnt = 1; }; //
smart_pointer<T>(const smart_pointer<T>& other) : pointer(other.pointer) {
// std::cout << ", *(other.cnt): " << *(other.cnt);
cnt = other.cnt;
cnt++;
} // Copy-constructor
int counter() const {
return cnt;
}
};
int main() {
// smart_pointer_examples();
std::string h("hello");
smart_pointer<std::string> p(&h);
std::cout << "p: " << p.counter();
smart_pointer<std::string> q(p);
std::cout << ", q: " << q.counter() << std::endl;
return 0;
}

Modifying an object also modifies all other objects of the same class

It's a long time ago since my last c++ project and now I'm stuck in a very simple problem. I create two objects and want to modify only one of them. Now I don't understand why the other object is also modified...
MainClass:
#include "testobject.h"
#include <iostream>
int main() {
TestObject o1;
TestObject o2;
std::cout << "object1 before: " << o1.getI() << std::endl;
std::cout << "object2 before: " << o2.getI() << std::endl;
o1.setI(2);
std::cout << "object1 after: " << o1.getI() << std::endl;
std::cout << "object2 after: " << o2.getI() << std::endl;
}
TestObjectClass:
#include "testobject.h"
int i;
int TestObject::getI() {
return i;
}
void TestObject::setI(int j) {
i = j;
}
The output is:
object1 before: 0
object2 before: 0
object1 after: 2
object2 after: 2
Why is i in object2 also set to 2?
The both objects refer to the common variable
int i;
declared in the global namespace. So once the variable is changed the class method
int TestObject::getI() {
return i;
}
will return the same value of the variable i for both objects.
Make the variable a data member of the class.
For example
class TestObject
{
//...
private:
int i;
};
Pay attention to that the member function getI should be declared with the qualifier const because it does not change the object itself
class TestObject
{
public:
int getI() const {
return i;
}
//...
};

Calling method that modifies a field while another method that uses that field is executing

I have a question regarding the outside modification of a running method.
Given this C++ class:
#include <iostream>
class Foo {
public:
Foo()
: runBar(true) {}
void bar() {
int i = 0;
while(this->runBar) {
std::cout << "Loop " << i++ << std::endl;
}
std::cout << "Loop done!" << std::endl;
}
void baz() {
this->runBar = false;
std::cout << "Field changed!" << std::endl;
}
private:
bool runBar;
};
And also given this main function:
int main(int argc, char* argv[]) {
Foo f;
f.bar();
f.baz();
return 0;
}
What happens when the call to Foo::baz() is made?
Thanks for the help!
Since you only have 1 thread of execution, and you do not have anything to change the while loop exit condition in the bar function, this code will loop forever. Your baz function will never be called.
Assuming you meant to call them from separate threads,
here is an example showing main modified to call the function from within a thread.
Foo is using a mutext to coordinate activity, like allowing the thread to finish printing before being terminated.
The join prevents termination of main from ending everything prematurely.
If you don't coordinate them in some way such as that, it would not possible to say with certainty what the sequence of events would be. Such is the nature of programming with multiple threads.
Either bar runs first in which case it prints, or else baz runs first in which case bar will not. Either is possible.
#include <iostream>
#include <mutex>
mutex aMutex; //<--
class Foo {
public:
Foo()
: runBar(true) {}
void bar() {
int i = 0;
while(this->runBar) {
aMutex.lock(); //<--
std::cout << "Loop " << i++ << std::endl;
aMutex.unlock(); //<--
}
std::cout << "Loop done!" << std::endl;
}
void baz() {
this->runBar = false;
aMutex.lock(); //<--
std::cout << "Field changed!" << std::endl;
aMutex.unlock(); //<--
}
private:
bool runBar;
};
#include <thread>
int main(int argc, char* argv[]) {
Foo f;
thread myThread { f.bar() }; //call it in a thread
f.baz();
myThread.join(); //<--
return 0;
}

Count resources in C++ RAII style

I would like to have a C++11 RAII component to count how many resources of a certain type are present in a multithreaded environment. I wrote the following:
#include <atomic>
#include <iostream>
using namespace std;
class AtomicCounter
{
public:
AtomicCounter(std::atomic< int > &atomic) : atomic(atomic) {
int value = ++this->atomic;
cerr << "incremented to " << value << endl;
}
~AtomicCounter() {
int value = --this->atomic;
cerr << "decremented to " << value << endl;
}
private:
std::atomic< int > &atomic;
};
int main() {
atomic< int > var;
var = 0;
AtomicCounter a1(var);
{
AtomicCounter a2(var);
cerr << "Hello!" << endl;
AtomicCounter a3(var);
}
cerr << "Good bye!" << endl;
return 0;
}
The idea is that I create an AtomicCounter object in each resource (for example, the main thread function) and this keeps the associated atomic variable updated.
Is this component correct, even when used in a multithreaded environment? Is there a standard component that already does this?

Performance difference between accessing local and class member variables

I have the following code in a class member function:
int state = 0;
int code = static_cast<int>(letter_[i]);
if (isalnum(code)) {
state = testTable[state][0];
} else if (isspace(code)) {
state = testTable[state][2];
} else if (code == OPEN_TAG) {
state = testTable[state][3];
} else if (code == CLOSE_TAG) {
state = testTable[state][4];
} else {
state = testTable[state][1];
}
switch (state) {
case 1: // alphanumeric symbol was read
buffer[j] = letter_[i];
++j;
break;
case 2: // delimeter was read
j = 0;
// buffer.clear();
break;
}
However, if state is a class member variable rather than local, the performance drops considerably (~ 5 times). I was reading about differences in accessing local variables and class members, but texts usually say that it affects performance very slightly.
If it helps: I am using MinGW GCC compiler with -O3 option.
I could not reproduce your observation, testing on x86_64 with both, VS10 and g++. The local variant is slightly faster, probably due to what Alan Stokes described in his comment, but at most ~10%. You should check your timing, try to rule out any other problems and best would be the reduce all your code to a very simple test-cast which still shows this behavior.
I think my test-case resembles your scenario quite good, at least like you described it:
#include <iostream>
#include <boost/timer.hpp>
const int max_iter = 1<<31;
const int start_value = 65535;
struct UseMember
{
int member;
void foo()
{
for(int i=0; i<max_iter; ++i)
{
if(member%2)
member = 3*member+1;
else
member = member>>1;
}
std::cout << "Value=" << member << std::endl;
}
};
struct UseLocal
{
void foo()
{
int local = start_value;
for(int i=0; i<max_iter; ++i)
{
if((local%2)!=0) /* odd */
local = 3*local+1;
else /* even */
local = local>>1;
}
std::cout << "Value=" << local << std::endl;
}
};
int main(int argc, char* argv[])
{
/* First, test using member */
std::cout << "** Member Access" << std::endl;
{
UseMember bar;
bar.member = start_value;
boost::timer T;
bar.foo();
double e = T.elapsed();
std::cout << "Time taken: " << e << "s" << std::endl;
}
/* Then, test using local */
std::cout << "** Local Access" << std::endl;
{
UseLocal bar;
boost::timer T;
bar.foo();
double e = T.elapsed();
std::cout << "Time taken: " << e << "s" << std::endl;
}
return 0;
}