I have a question about the 'atomic_fetch_sub_explicit' operations in c++11. I have run the next code thousands of times, and only observed two possible outputs: "data: 0 1" or "data: 1 0". I want to know is it possible to generate output: "data: 1 1"?
#include <atomic>
#include <thread>
using namespace std;
std::atomic<int> x;
int data1, data2;
void a() {
data1 = atomic_fetch_sub_explicit(&x, 1, memory_order_relaxed);
}
void b() {
data2 = atomic_fetch_sub_explicit(&x, 1, memory_order_relaxed);
}
int main() {
x = 1;
std::thread t1(a);
std::thread t2(b);
t1.join(), t2.join();
printf("data: %d %d\n", data1, data2);
}
Related
I want the output to be: 1 2 2 2
But why is the output: 1 2 3 4
What's wrong with this code?
#include <iostream>
using namespace std;
int arr[] = {0};
int pluss(int ar[],int a){
ar[0]++;
cout<<ar[0]<<endl;
if(a==0){
pluss(ar,a+1);
pluss(ar,a+1);
pluss(ar,a+1);
}
}
int main() {
pluss(arr,0);
return 0;
}
EDIT: So, the "ar" is global and not local to one child function? how to make it so the "ar" is only local to one child function? I mean: the "ar" in the first pluss(ar,1) is different from the "ar" in the second pluss(ar,2)?
Your code is equivalent of :
int main() {
pluss(arr,0);
pluss(arr,1);
pluss(arr,1);
pluss(arr,1);
return 0;
}
Since each call to pluss definitely increments the array element, before printing it, expected output is 1, 2, 3, 4.
how to make it so the "ar" is only local to one child function?
If you don't like to pass each array element as integer value, you could wrap the array in a struct, since structures are passed by value rather than by reference.
#include <iostream>
using namespace std;
struct s { int a[1]; } arr = {0};
int pluss(struct s ar, int a)
{
ar.a[0]++;
cout <<ar.a[0] <<endl;
if (a==0)
{
pluss(ar, a+1);
pluss(ar, a+1);
pluss(ar, a+1);
}
}
int main()
{
pluss(arr, 0);
return 0;
}
I am reading text from a text file and need to know the number of characters in the file in total. I thought this should work but it always seems to be overcounting. For example I typed this into my text file:
thisisatestthisisa
thisisa
And the program returned a total of 32.
#include <iostream>
#include <fstream>
#include <string>
#include <ostream>
using namespace std;
int main() {
fstream inFile;
string inputString;
inFile.open("text.txt", ios::in);
unsigned int total = 0;
if (inFile) {
while (inFile)
{
getline(inFile, inputString);
unsigned int tempStringLength = inputString.length();
total += tempStringLength;
}
cout << "total is: " << total << endl;
}
else {
cerr << "Unable to open file text.txt";
exit(1);
}
return 0;
}
You are double-counting the last line in the file.
Because you are using while(inFile) instead of while(getline(inFile, inputString)) the stream's state is not invalidated until the call to getline(...):
Walking through the loop will make this obvious:
Iteration 1:
unsigned int total = 0;
//...
while (inFile) //True
{
getline(inFile, inputString); //inFile: True, inputString: thisisatestthisisa
unsigned int tempStringLength = inputString.length(); //18
total += tempStringLength; //18
}
//...
Iteration 2:
//...
while (inFile) //True
{
getline(inFile, inputString); //inFile: True, inputString: thisisa
unsigned int tempStringLength = inputString.length(); //7
total += tempStringLength; //25
}
//...
Iteration 3:
//...
while (inFile) //True
{
getline(inFile, inputString); //inFile: EOF, inputString: thisisa (not modified)
unsigned int tempStringLength = inputString.length(); //7
total += tempStringLength; //32
}
//...
inFile now returns false because the EOF was reached and your loop terminates. Printing 32 as the length.
Long story short: Don't use the file state as a loop terminator. Use the actual read, either getline or operator>> depending on the situation.
#include <cstdint>
#include <cstring>
template<typename T>
T oph_(const char *s){
constexpr std::size_t MAX = sizeof(T);
const std::size_t size = strnlen(s, MAX);
T r = 0;
for(auto it = s; it - s < size; ++it)
r = r << 8 | *it;
return r;
}
inline uint64_t oph(const char *s){
return oph_<uint64_t>(s);
}
int main(){
uint64_t const a = oph("New York City");
uint64_t const b = oph("Boston International");
return a > b;
}
I want to convert first 8 characters from const char * to uint64_t so I can easily compare if two strings are greater / lesser.
I am aware that equals will semi-work.
However I am not sure if this is most efficient implementation.
I want the implementation to work on both little and big endian machines.
This is a C implementation, that should be faster that your implementation, but I still need to use strncpy which should be the bottleneck
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <byteswap.h>
union small_str {
uint64_t v;
char buf[8];
};
static uint64_t fill_small_str(const char *str)
{
union small_str ss = { 0 };
strncpy(ss.buf, str, 8);
#if defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
return ss.v;
#else
return bswap_64(ss.v);
#endif
}
int main(void)
{
uint64_t const a = fill_small_str("Aew York City");
uint64_t const b = fill_small_str("Boston International");
printf("%lu ; %lu ; %d\n", a, b, (a < b));
return 0;
}
I'm trying to create a vector of std::function and then pass that vector to a function. I also need to pass arguments to the function objects, so I'm using std::bind. Here is the code:
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void execute(vector<function<void (int)>>& fs) {
for (auto& f : fs)
f();
}
void func(int k) {
cout << "In func " << k << endl;
}
int main()
{
int i = 1;
vector<function<void (int)>> x;
auto f1 = bind(func, i);
//f1(); // this does call intended function
x.push_back(f1);
execute(x);
}
but this gives following error:
function_tmpl.cpp: In function ‘void execute(std::vector >&)’:
function_tmpl.cpp:14:5: error: no match for call to ‘(std::function) ()’
f();
^
In file included from function_tmpl.cpp:1:0:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/functional:2142:11: note: candidate is:
class function
^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/functional:2434:5: note: _Res std::function::operator()(_ArgTypes ...) const [with _Res = void; _ArgTypes = {int}]
function::
^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/functional:2434:5: note: candidate expects 1 argument, 0 provided
If I call f() inside main(), that works fine, which means that the function has bound with the arguments, but it's not working when passed to another function as argument
You are using a vector of void functions with a single int argument: vector<function<void (int)>>, but you are actually pushing void(void) functions. All you need to do is to change the element type of the vector to vector<function<void (void)>>. Bind works roughly like this:
given:
void f1(int i) { printf("%d", i); }
bind(f1, 1) returns a new function f2:
void f2()
{
f1(1);
}
and since you are pushing f2, the vector should store void(void) functions.
After binding, the type of function has become to void(). So change the type of vector to vector<function<void ()>>, you'll get it.
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void execute(vector<function<void ()>>& fs) {
for (auto& f : fs)
f();
}
void func(int k) {
cout << "In func " << k << endl;
}
int main()
{
int i = 1;
vector<function<void ()>> x;
auto f1 = bind(func, i);
x.push_back(f1);
execute(x);
}
result:
In func 1
LIVE
The return type of std::bind is unspecified. Hence you cannot expect std::bind to return a variable of same type as std::function<void(int)>. Use decltype and templates to resolve.
Here is an example
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename T>
void execute(vector<T>& fs) {
for (auto& f : fs)
f();
}
void func(int k) {
cout << "In func " << k << endl;
}
int main()
{
int i = 1;
auto f1 = bind(func, i);
vector<decltype(f1)> x; //deduce type of f1
x.push_back(f1);
execute(x);
}
f is of type
function<void (int)>&
so the compiler expects you to provide a parameter, like this:
f(1)
The following is a code for sorting numbers based on quicksort in C. To optimize for speed, scanf() has been replaced by fread(). But on printing the sorted list, all garbage values come out. The exact problem statement is on :http://www.codechef.com/problems/TSORT
#define SIZE 32768
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b)
{
return (*(unsigned long *)a-*(unsigned long *)b);
}
int main()
{
char buffer[SIZE];
register int readBytes=0;
unsigned long bufferCounter=0, bufferedInput=0;
unsigned long * array, t, i;
scanf("%lu", &t); fflush(stdin);
array=(unsigned long *) malloc(sizeof(long)*t);
i=-1;
while(readBytes=fread(buffer, sizeof(char), SIZE, stdin)>0)
{
for(bufferCounter=0; bufferCounter<readBytes; bufferCounter++)
{
if(buffer[bufferCounter]=='\n' || buffer[bufferCounter]==' ')
{
array[++i]=bufferedInput;
bufferedInput=0;
}
else bufferedInput=bufferedInput*10+(buffer[bufferCounter]-'0');
}
}
qsort(array, t, sizeof(long), compare);
for(i=0; i<t; i++)
{
printf("%lu\n", array[i]);
}
return 0;
}
The code is compiled in Codeblocks and the input is piped from a file.
The input file is :
5
5
3
6
7
1
The output obtained is:
5050160
5056368
1465662019
1868852841
1935438711
What is the problem with my code?