Do I have to return `NULL` for thread function when I use the detached pthread in linux?
For example:
void* thread(void *arg)
{
return NULL;
}
int main()
{
pthread_attr_t attr;
pthread_t th;
pthread_attr_setdetachstate(pthread_attr_t &attr, PTHREAD_CREATE_DETACHED);
pthread_create(&th, &attr, thread, NULL);
}
Because of it's a detached thread, I can not receive the funtion retrun by pthread_join
. So I think the return of thread is useless, should I return NULL
? If I don't return NULL
, will it cause some bug?
1 answer
-
answered 2020-11-25 07:05
eerorika
should I return NULL?
You can return
nullptr
or any other value whether the thread is detached or not.If I don't return NULL, will it cause some bug?
If you don't return anything then the behaviour of the program will be undefined.
P.S. The C++ standard library has portable wrappers for threads which allow you to not depend on any particular operating system. I recommend using those instead of system specific API.
See also questions close to this topic
-
How to trim last four character from the input in bash shell?
I intend to automate compile and run process in C++, I wrote the following code as
compile-run.sh
#! /bin/bash clang++ $1.cpp -o $1.out && ./$1.out
I put this compile-run.sh in /usr/local/bin for global usage, and when I type the command
compile-run.sh XXX.cpp
, it intend to compile and run the specified cpp file. But the problem now is I have to manually removed ".cpp
" in the command.Is there any way to trim the last X number of character and assign to a variable in general?
Is there any way to trim the.cpp
and apply trimmed $1 in the code?
Is there better way to automate compile and run process? -
c++ segmentation fault and Trace/breakpoint trap when using Dynamic memory allocation
I am practicing Dynamic memory allocation in C++. I wanna enter some word which length is less than 10, and when I enter "-1", it will print the word I have entered before.
But when I enter more than three words, it will give me an Trace/breakpoint trap or segmentation fault. I use gdb-peda to check my code, it said "double free detected in tcache 2", I think the problem is the "delete" part in my code, but I dont know how to correct it.
this is my code:
#include <iostream> #include <limits> using namespace std; int counter = 0; //be used to count how many times we have entered char **ins(); int main() { auto dict = ins(); //Total list for ( int i = 0; i < counter; i++ ) { for ( int j = 0; j < 10; j++ ) { if ( *( *( dict + i ) + j ) == '\0' ) //if the word is null,print the word and go to next word break; cout << *( *( dict + i ) + j ); } cout << endl; } for ( int i = 0; i < counter; i++ ) delete[] dict[i]; //delete the total list system( "pause" ); return 0; } char **ins() { auto dict = new char *[1](); //total list auto cpdict = new char *[1](); //copy list while ( 1 ) { auto word = new char[10](); //a list be used to store the entered word (length<10) cout << "input word: "; cin.get( word, 10, '\n' ); //get the entered word in the list if ( word[0] == '-' && word[1] == '1' ) { //if enter "-1" , delete the copy list and return the total list delete[] cpdict; return dict; } counter++; //plus one of the times of entering delete[] dict; //delete the old total list auto dict = new char *[counter](); //create a new total list, the lenth is one more than the old total list for ( int i = 0; i < counter - 1; i++ ) *( dict + i ) = *( cpdict + i ); //copy the stuffs in old copy list to new total list *( dict + counter - 1 ) = word; //copy the word we just enter into total list delete[] cpdict; //delter the old copy list auto cpdict = new char *[counter](); //create a new copy list for ( int i = 0; i < counter; i++ ) *( cpdict + i ) = *( dict + i ); //copy the stuffs in new total list to new copy list cin.clear(); cin.ignore( numeric_limits<std::streamsize>::max(), '\n' ); } }
My imagine input and output is like:
input word: aaa input word: bbb input word: ccc input word: ddd input word: -1
output:
aaa bbb ccc ddd
-
Qt Linux to Windows transition: Error in macro substitution
I have a Qt project (Version 5.14.2), which is building just fine under Linux. Now I would like to provide it on Windows as well. However, I have some trouble getting it built. The following error is thrown:
Error: Cannot find = after : in macro substitution.
And then a line in the makefile. When I go to the line there is this command:
443 {C:\Users\Alex\Documents\GitHub\control-station\src\aircraft}.cpp{obj\}.obj:: 444 $(CXX) -c $(CXXFLAGS) $(INCPATH) -Foobj\ @<< 445 $< 446 <<
I have no prior experience with windows, so this error leaves me clueless. There is another error following:
Kit Desktop Qt 5.14.2 MSVC2017 64bit has configuration problems.
It looks like this is consecutive of the one prior, but I am not sure. Do you have any suggestions what to check? It seems to be a macro error, but I don't know where to start looking?
-
Arch- Linux installation successful but not booting
l have installed arch- linux successfully using the bios way and every just worked fine. But it doesn't boot ,what could be the problem
-
Problem when Handling repeated error values on php and mysql
I have a PHP program that connect to a MariaDB databse.
I upload name as "numbers" and i defined the value as UNIQUE so I don´t want to be repeatated.
However I would like to handle the error when a vlaue is repeated:
This is the table I created:
Table in MariaDB
create table test( -> id int NOT NULL AUTO_INCREMENT, -> name varchar(255) UNIQUE, -> date DATE NOT NULL, -> PRIMARY KEY (id) -> );
This is the script in PHP:
$host = "localhost"; $db_name = "xxx"; $username = "xxx"; $password = "xxx"; $connection = null; $dt1=date("Y-m-d"); try{ $connection = new PDO("mysql:host=" . $host . ";dbname=" . $db_name, $username, $password); $connection->exec("set names utf8"); } catch(PDOException $exception){ echo "Connection error: " . $exception->getMessage(); } function saveData($name, $dt1){ global $connection; $query = "INSERT INTO test(name, date) VALUES( :name, :date )"; $callToDb = $connection->prepare( $query ); $name=htmlspecialchars(strip_tags($name)); //$dt1=htmlspecialchars(strip_tags($dt1)); $callToDb->bindParam(":name", $name); $callToDb->bindParam(":date", $dt1); if($callToDb->execute()){ //return '<h3 style="text-align:center;">registration submmited!</h3>'; //if (!$callToDb->execute()) { // if ($callToDb->errno == 1062) { // return '<h3 style="text-align:center;">VALUE REPEATED!</h3>'; // } // else{ return '<h3 style="text-align:center;">registration submmited!</h3>'; // } } } if( isset($_POST['submit'])) { $name = htmlentities($_POST['name']); $dt1 = htmlentities($_POST['date']); //then you can use them in a PHP function. $result = saveData($name, $dt1); echo $result; } else{ echo '<h3 style="text-align:center;">A very detailed error message</h3>'; } //header("location:javascript://history.go(-1)"); }
the code part after
if($callToDb->execute()){
it is commented because it is not working but I would like to just show a message when the vlaue is repeated. The same than when a vlaue is registrated correctly.The issue to handle duplicate error is in this part which at the moment I am not using in my code as is not working fine:
if (!$callToDb->execute()) { if ($callToDb->errno == 1062) { return '<h3 style="text-align:center;">VALUE REPEATED!</h3>'; } else{ return '<h3 style="text-align:center;">registration submmited!</h3>'; } }
Any idea why this part of the code it is not working?
-
httplib2 :- argument should be integer or bytes-like object, not 'str'
I am using Google Indexing API, and I am getting this error
argument should be integer or bytes-like object, not 'str'
I am implementing the API on the Django server when I run it on my local machine it runs just fine. but when I put it on pythonanywhere it is giving me the above error. I don't know what's the reason for this error. here is the function
def demo(request): context = {} if request.GET: link = request.GET.get('link') key = request.GET.get('key') if link and key: context = { 'link': link, 'key': key, } try: key = json.loads(key) except: return render(request, 'google_api_demo/index.html', context) scope = [ "https://www.googleapis.com/auth/indexing" ] endpoint = "https://indexing.googleapis.com/v3/urlNotifications:publish" credentials = ServiceAccountCredentials.from_json_keyfile_dict(key, scopes=scope) http = credentials.authorize(httplib2.Http()) content = bytes(str({ "url": f"{link}", "type": "URL_UPDATED", }), encoding='utf-8') response, content = http.request(endpoint, method="POST", body=content) context['response'] = response context['content'] = content return render(request, 'google_api_demo/index.html', context) return render(request, 'google_api_demo/index.html', context)
-
Why does my thread stop after printing one line on its second run?
I'm using pthreads and I'm trying to run an infinite loop on the main thread. The loop is supposed to print out "Hello world!" 10 times, then create a separate thread that writes "Hello moon!" 10 times, and then start over.
For some reason the output of my program is (always):
Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello moon! Hello moon! Hello moon! Hello moon! Hello moon! Hello moon! Hello moon! Hello moon! Hello moon! Hello moon! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello world! Hello moon!
instead of running forever.
The code follows:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #define SEC_IN_NSEC(x) (x * 1000000000) pthread_mutex_t mutex; void *hello_moon(void *param); int main(int argc, char **argv) { pthread_t moon_tid; pthread_mutex_init(&mutex, NULL); while(1) { pthread_mutex_lock(&mutex); for(int i = 0; i < 10; i++) { printf("Hello world!\n"); sleep(1); } pthread_mutex_unlock(&mutex); pthread_create(&moon_tid, NULL, hello_moon, NULL); pthread_join(moon_tid, NULL); } pthread_mutex_destroy(&mutex); } void* hello_moon(void *param) { struct timespec ts; ts.tv_nsec = SEC_IN_NSEC(0.2); // 0.2 s in ns pthread_mutex_lock(&mutex); for(int i = 0; i < 10; i++) { printf("Hello moon!\n"); nanosleep(&ts, NULL); } pthread_mutex_unlock(&mutex); pthread_exit(0); }
Does anyone have a clue why this is happening?
UPDATE: I commented out the sleep and nanosleep calls and ran it, then it loops as expected. I still want the delay between prints, however.
-
Multithreading Problem - Not understanding how the concept of printf implemented in concurrency
Im struggling a problem in multithreading which I have two threads running over one printf ; and I don't know how exactly those four cases that's already explained in that video are correct?! could anyone please illustrate more about them? appreciated for any help to understand why what's explained here to that problem is correct ! I'm attaching down the video of the problem: enter link description here
Appreciated for any help for how those 4 cases of the problem are correct .
-
Setting priority with pthread_attr_setschedparam doesn't seem to change NICE value
I would like to create a thread that has lower priority than its parent.
I came up with following code with a hope that the thread has 5 for its NICE value.
pthread_attr_t tattr; struct sched_param param; if(pthread_attr_init(&tattr) != 0) { print("Thread_Create: Error pthread_attr_init \n"); } if(pthread_attr_getschedparam(&tattr, ¶m) != 0) { print("Thread_Create: Error pthread_attr_getschedparam \n"); } if(pthread_attr_setschedpolicy(&tattr, SCHED_RR) != 0) { print("Thread_Create: Error pthread_attr_setschedpolicy \n"); } param.sched_priority = 5; if(pthread_attr_setschedparam(&tattr, ¶m) != 0) { GeaLog(GeaLogLevel_Emerg, "Thread_Create: Error pthread_attr_setschedparam \n"); } pthread_create(&instance->_private.thread, &tattr, Run, instance);
Now, I would like to check if it is effective. I executed
ps -m -l [parent pid]
# ps -m -l 10802 F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 0 - 0 10802 1 12 - - - 10362 - pts/1 0:18 /usr/crank/build 0 S 0 - - 12 80 0 - - hrtime - 0:18 - 1 S 0 - - 0 80 0 - - hrtime - 0:00 -
I was expecting NI to be 5 but it's 0. Do you have any idea what I am missing?