sched_setscheduler是针对所有线程还是主线程?

时间:2016-07-04 23:08:47

标签: c linux scheduled-tasks thread-priority

我有以下来源喜欢SCHED_RR优先级为90:

func CheckUser(username: String, password: String, server: String){
let port = "8443"
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let userPasswordString = NSString(format: "%@:%@", username, password)
let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
let authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders?.removeAll()
config.HTTPAdditionalHeaders = ["Authorization" : authString]
config.timeoutIntervalForRequest = 10.0

// create the user request
let userUrlString = NSString(format: "https://%@:%@/webserver/user/%@", server, port, username)
let userUrl = NSURL(string: userUrlString as String)
userRequest.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
userRequest.URL = userUrl!
userRequest.HTTPMethod = "GET"
userRequest.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
userSession = NSURLSession(configuration: config, delegate: self, delegateQueue:NSOperationQueue.mainQueue())

//Send User Request to the server and populate labels with response.
let task = userSession.dataTaskWithRequest(userRequest) { (data, response, error) in
    dispatch_async(dispatch_get_main_queue(), { () -> Void in

        if error?.code != nil{
            print("ERROR: \(error!.localizedDescription)")
            self.DisplayAlert("Error", message: error!.localizedDescription)
        }else{
            _ = NSString (data: data!, encoding: NSUTF8StringEncoding)
            let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            let accessDenied = Bool(dataString?.rangeOfString("HTTP Status 403").location != NSNotFound)
            let authFailure = Bool(dataString?.rangeOfString("HTTP Status 401").location != NSNotFound)

            if (authFailure || accessDenied) {
                print("\(NSDate()): Unsuccessful Password Authentication Attempt for user: \(NSUserDefaults.standardUserDefaults().valueForKey("userName")!)")
                self.DisplayAlert("Access Denied", message: "Please Verify Your Credentials")
            }else{
                print("\(NSDate()): Successful Password Authentication for user: \(NSUserDefaults.standardUserDefaults().valueForKey("userName")!)")
                self.performSegueWithIdentifier("authenticated", sender: self)
            }
        }
    })
}.resume()
}

虽然shell“top”,我可以看到该进程的PR为-91,看起来很有效, 据我所知,在Linux中,thread1和thread2以及thread3是不同的任务 从主线程,他们只是共享相同的虚拟内存,我想知道 在这个测试中,我是否需要添加

if NSUserDefaults.standardUserDefaults().valueForKey("touchIDPreferenceSet") == nil  && CheckTouchIDCapable() {
    DisplayTouchIDQuestion("Use Touch ID?", message: "Would you like to use touch ID to login?")
}else{
    usernameField.enabled = false
    passwordField.enabled = false
    serverNameField.enabled = false
    activityIndicator.startAnimating()
    CheckUser(usernameField.text, password: passwordField.text, server: serverNameField.text)
}

对于所有thread1,thread2和thread3,以便可以安排所有这3个 与SCHED_RR?!或者我不需要这样做?!我怎么能观察到 thread1,thread2和thread3线程是SCHED_RR还是SCHED_OTHER?!

编辑:

int main(int argc, char** argv)
{
    const char *sched_policy[] = {
    "SCHED_OTHER",
    "SCHED_FIFO",
    "SCHED_RR",
    "SCHED_BATCH"
    };
    struct sched_param sp = {
        .sched_priority = 90
    };
    pid_t pid = getpid();
    printf("pid=(%d)\n",pid);
    sched_setscheduler(pid, SCHED_RR, &sp);
    printf("Scheduler Policy is %s.\n", sched_policy[sched_getscheduler(pid)]);

    pthread_t tid ;
    pthread_create(&tid , NULL, Thread1 , (void*)(long)3);
    pthread_create(&tid , NULL, Thread2 , (void*)(long)3);
    pthread_create(&tid , NULL, Thread3 , (void*)(long)3);
    while(1)
        sleep(100);
}

会看到:

pthread_setschedparam(pthread_self(), SCHED_RR, &sp);

我怎么能确定这只是主线程?或pid 7187中的所有主题 是SCHED_RR政策吗?再次,如何观察它?!

1 个答案:

答案 0 :(得分:3)

在创建任何新线程之前,您应检查(并设置,如果需要)调度程序继承属性。

int pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inheritsched);

int pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched);

pthread_attr_getinheritsched()将在inheritsched指向的变量中存储两个可能的值之一:

  •   

    PTHREAD_INHERIT_SCHED - 使用attr创建的线程
      从创建线程继承调度属性;该   attr中的调度属性将被忽略。

  •   

    PTHREAD_EXPLICIT_SCHED - 使用attr创建的线程   他们的调度属性来自于指定的值   属性对象。

如果您希望每个新创建的线程都继承调用任务的调度程序属性,则应设置PTHREAD_INHERIT_SCHED(如果尚未设置)。

另请注意:

  

新的inherit-scheduler属性的默认设置   初始化的线程属性对象是 PTHREAD_INHERIT_SCHED

<强>参考

$ man pthread_setschedparam
$ man pthread_attr_setinheritsched
  • (Blockquoted资料是从Linux man-pages项目的3.74版本的部分复制而来的。)